Home » Android » java – convert to unsigned char and unsigned short in Android-Exceptionshub

java – convert to unsigned char and unsigned short in Android-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I have to convert my bytes to unsigned char and unsigned short , it is done like this in iOS

latitude = (unsigned char)(bytebuffr.getchar(0)) + ((unsigned short)(bytebuffr.getchar(1)& 0xF)) << 8);

How can I achieve this in my android code. please help
already tried this in android but not working,

lattitude = (short) ((getUnsignedByte((byte) (bb.getChar(0) & 0xFF))) +
                    getUnsignedByte((byte) ((bb.getChar(1) & 0x0F))) << 8);

bb is bytebuffer and bb.getchar is giving me the bytes which is being read from bytebuffer

How to&Answers:

You don’t need to convert from char to short in this case. Since bb is a ByteBuffer, use getShort if you want to read two bytes from the buffer and use them as a signed 16-bit number. Use getChar if you need to read two bytes from the buffer (not one!) and use them as an unsigned 16-bit number. I suspect you’re thinking that getChar only reads a single byte. It doesn’t. char is 16 bits wide. Also, char is an unsigned integral type in Java. Although it’s used to represent characters (loosely) in strings, it’s an integral (whole number) type. The integral types are:

  • byte: 8-bit signed: -128 to 127, inclusive
  • short: 16-bit signed; -32768 to 32767, inclusive
  • char: 16-bit unsigned: 0 to 65535, inclusive (aka '\u0000' to '\uffff')
  • int: 32-bit signed: -2147483648 to 2147483647, inclusive
  • long: 32-bit signed: -9223372036854775808 to 9223372036854775807, inclusive

If you did need to convert: char is an unsigned 16-bit type. short is a signed 16-bit type. To use the same bits in a short as you have in a char, you do this:

short s = (short)ch;

No need for masking off the first byte or anything like that.