在 Java 中将 INT(0-255) 转换为 UTF8 字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3596004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 02:34:25  来源:igfitidea点击:

Convert INT(0-255) to UTF8 char in Java

javainteger

提问by Nils

since I need to control some devices, I need to send some bytes to them. I'm creating those bytes by putting some int values together (and operator), creating a byte and finally attaching it to a String to send it over the radio function to the robot.

因为我需要控制一些设备,所以我需要向它们发送一些字节。我通过将一些 int 值(和运算符)放在一起来创建这些字节,创建一个字节,最后将它附加到一个字符串以通过无线电功能将其发送给机器人。

Unfortuantely Java has some major issues doing that (unsigned int problem)

不幸的是,Java 有一些主要问题(unsigned int 问题)

Does anybody know, how I can convert an integer e.g.

有谁知道,我如何转换一个整数,例如

x = 223; 

to an 8-bit character in Java to attach it to a String ?

到 Java 中的 8 位字符以将其附加到 String ?

char = (char)x;   // does not work !! 16 bit !! I need 8 bit !

回答by kennytm

A charis16-bit in Java. Use a byteif you need an 8-bit datatype.

A在 Java 中char16 位的。byte如果需要 8 位数据类型,请使用 a 。

See How to convert Strings to and from UTF8 byte arrays in Javaon how to convert a byte[]to Stringwith UTF-8 encoding.

请参阅如何将字符串转换为从UTF8字节数组在Java中如何转换一byte[]String与UTF8编码。

回答by btown

Sending a java.lang.String over the wire is probably the wrong approach here, since Strings are always 16-bit (since Java was designed for globalization and stuff). If your radio library allows you to pass a byte[] instead of a String, that will allow you to send 8-bit values without needing to worry about converting to UTF8. As far as converting from an int to an unsigned byte, you'll probably want to look at this article.

通过网络发送 java.lang.String 在这里可能是错误的方法,因为字符串总是 16 位的(因为 Java 是为全球化而设计的)。如果您的无线电库允许您传递一个 byte[] 而不是一个字符串,那么您就可以发送 8 位值而无需担心转换为 UTF8。至于从 int 转换为无符号字节,您可能想看看这篇文章

回答by Error

int to array of bytes

int 到字节数组

public byte[] intToByteArray(int num){
      byte[] intBytes = new byte[4];
      intBytes[0] = (byte) (num >>> 24);
      intBytes[1] = (byte) (num >>> 16);
      intBytes[2] = (byte) (num >>> 8);
      intBytes[3] = (byte) num;
      return intBytes;
}

note endianness here is big endian.

注意这里的字节序是大字节序。