简体   繁体   中英

Converting int to byte[]

I'm reading a value from the screen in Android and try to convert it to a byte[] to send it over Bluetooth but every time I it takes 128 from the screen, it converts it to -128 in the byte[] and than I don't get anything on the other side..What is the problem..Why is it giving negative number?..

This is the convert code :

ByteBuffer.allocate(4).putInt(yourInt).array();

EDIT : On the other side I have to transform the byte[] to String.

And another problem..If I lower the number in the allocate() I get a BufferOverflowException even though I use only 1 position in the array. Why?

EDIT 2 : I'm working with 8bit numbers (0-255)

public static void main(String[] args) {
    byte[] num = BigInteger.valueOf(-2147483648).toByteArray();
        System.out.println(new BigInteger(num).intValue());
    }

if you want to transfer only one byte, valued 0-255, then

public static void main(String[] args) {
    for(int i=0; i<=255; i++){
        byte a = (byte) i;
        byte[] num = new byte [] {(byte) a};
        System.out.println(num[0] + " : " + i + " : " + ((256+num[0]) % 256));
    }
}

The second code will convert a byte variable to equal integer output.

The reason the code is doing this is because your integer (128) looks like 1000000 in binary with a bunch of leading zeroes. Since all Java primitives are signed, the leading bit is 0 and this comes out OK. However, when you convert to bytes the leading bit gets interpreted as the sign bit, so the last byte is interpreted as negative.

The documentation is also pretty clear that putInt() writes all 4 bytes of the integer to the buffer, instead of only the bytes which are "used".

You are seeing the correct values in the ByteBuffer. The last byte of the buffer has the byte value 0x80, which if you sign extend to a longer int value APPEARS as -128 when displaying in a dumb terminal.

BYTE VALUES
1000 0000 

This hight bit typically designates a negative number in signed byte/short/int systems.

If you convert this signed byte to a larger type like an int by just prepending 1 bits, you would see this:

1111 1111 1111 1111 1111 1111 1000 0000 

Which indicates -128 as a signed int.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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