处理:如何将 char 数据类型转换为其 utf-8 int 表示? [英] Processing: How to convert a char datatype into its utf-8 int representation?

查看:83
本文介绍了处理:如何将 char 数据类型转换为其 utf-8 int 表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在 Processing 中将 char 数据类型转换为其 utf-8 int 表示?

How can I convert a char datatype into its utf-8 int representation in Processing?

所以如果我有一个数组 ['a', 'b', 'c'] 我想获得另一个数组 [61, 62, 63].

So if I had an array ['a', 'b', 'c'] I'd like to obtain another array [61, 62, 63].

推荐答案

在我回答之后,我想出了一种更简单、更直接的方法来转换为您想要的数字类型.你想要的 'a' 是 61 而不是 97 等等.看到 61 是十进制 97 的十六进制表示并不难.所以你需要做的就是将你的字符输入到一个特定的方法中,如下所示:

After my answer I figured out a much easier and more direct way of converting to the types of numbers you wanted. What you want for 'a' is 61 instead of 97 and so forth. That is not very hard seeing that 61 is the hexadecimal representation of the decimal 97. So all you need to do is feed your char into a specific method like so:

Integer.toHexString((int)'a');

如果你有一个像这样的字符数组:

If you have an array of chars like so:

char[] c = {'a', 'b', 'c', 'd'};

然后你可以这样使用上面的:

Then you can use the above thusly:

Integer.toHexString((int)c[0]);

等等等等.

编辑

根据下面评论中的 v.k. 示例,您可以在处理中执行以下操作:

As per v.k.'s example in the comments below, you can do the following in Processing:

char c = 'a';

以上内容会以字符串形式为您提供字符的十六进制表示.

The above will give you a hex representation of the character as a String.

// to save the hex representation as an int you need to parse it since hex() returns a String
int hexNum = PApplet.parseInt(hex(c));

// OR

int hexNum = int(c);

为了 OP 和下面评论者的利益.即使你在答案中使用了我之前的建议,你也会得到 97,因为 97 是十六进制 61 的十进制表示.看到 UTF-8 与 value 的前 127 个 ASCII 条目值匹配,我不明白为什么无论如何,人们会期待任何不同的事情.对于 UnsupportedEncodingException,一个简单的解决方法是将语句包装在 try/catch 块中.然而,没有必要看到上面以更简单的方式直接回答了这个问题.

For the benefit of the OP and the commenter below. You will get 97 for 'a' even if you used my previous suggestion in the answer because 97 is the decimal representation of hexadecimal 61. Seeing that UTF-8 matches with the first 127 ASCII entries value for value, I don't see why one would expect anything different anyway. As for the UnsupportedEncodingException, a simple fix would be to wrap the statements in a try/catch block. However that is not necessary seeing that the above directly answers the question in a much simpler way.

这篇关于处理:如何将 char 数据类型转换为其 utf-8 int 表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆