简体   繁体   English

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

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

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值放在一起(和运算符)来创建这些字节,创建一个字节并最终将其附加到String以通过无线电函数将其发送到机器人。

Unfortuantely Java has some major issues doing that (unsigned int problem) 不幸的是Java有一些主要问题(unsigned int问题)

Does anybody know, how I can convert an integer eg 有谁知道,我如何转换整数,例如

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 !

A char is 16-bit in Java. Java中的char 16位的。 Use a byte if you need an 8-bit datatype. 如果需要8位数据类型,请使用一个byte

See How to convert Strings to and from UTF8 byte arrays in Java on how to convert a byte[] to String with UTF-8 encoding. 请参阅如何将字符串转换为Java中的UTF8字节数组,以及如何将byte[]转换为使用UTF-8编码的String

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). 通过线路发送java.lang.String可能是错误的方法,因为字符串总是16位(因为Java是为全球化和东西而设计的)。 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. 如果您的无线电库允许您传递byte []而不是String,那么您将无需担心转换为UTF8就可以发送8位值。 As far as converting from an int to an unsigned byte, you'll probably want to look at this article . 至于从int转换为无符号字节,您可能希望查看本文

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. 注意这里的字节序是大端。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM