3

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.

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

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 ?

char = (char)x;   // does not work !! 16 bit !! I need 8 bit !
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Nils
  • 1,705
  • 6
  • 23
  • 32
  • possible duplicate of [Android java conversion problem](http://stackoverflow.com/questions/3595373/android-java-conversion-problem) – trashgod Aug 30 '10 at 01:17
  • 3
    Note that an UTF-8 character is **not** an 8-bit character. UTF-8 is a specific encoding for Unicode characters. A character can take up multiple bytes in UTF-8. In fact, this question doesn't have anything to do with UTF-8. – Jesper Aug 30 '10 at 13:50
  • [this answer will help you get if not what you want but could give you a clue](https://stackoverflow.com/a/44385153/4617869) – connelblaze Jun 06 '17 at 08:39

3 Answers3

1

A char is 16-bit in Java. Use a byte if you need an 8-bit datatype.

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.

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
0

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.

btown
  • 2,273
  • 3
  • 27
  • 38
0

int to array of bytes

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.

Error
  • 820
  • 1
  • 11
  • 34