简体   繁体   English

将int转换为byte []

[英]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?.. 我正在从Android屏幕上读取一个值,并尝试将其转换为byte []以通过蓝牙发送该值,但是每次我从屏幕上获取128时,它将在byte []中将其转换为-128,然后我什么都没得到。.是什么问题。.为什么给负数?

This is the convert code : 这是转换代码:

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

EDIT : On the other side I have to transform the byte[] to String. 编辑:另一方面,我必须将byte []转换为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. 另一个问题..如果我降低了allocate()的数字,即使我仅在数组中使用1个位置,我也会得到BufferOverflowException。 Why? 为什么?

EDIT 2 : I'm working with 8bit numbers (0-255) 编辑2:我正在使用8位数字(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 如果您只想传输一个字节,值为0-255,则

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. 代码执行此操作的原因是因为整数(128)看起来像二进制的1000000 ,带有一堆前导零。 Since all Java primitives are signed, the leading bit is 0 and this comes out OK. 由于所有Java原语都经过签名,因此前导位为0,这样就可以了。 However, when you convert to bytes the leading bit gets interpreted as the sign bit, so the last byte is interpreted as negative. 但是,当转换为字节时,前导位将被解释为符号位,因此最后一个byte被解释为负数。

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". 文档也很清楚, putInt()将整数的所有4个字节写入缓冲区,而不是仅将“已使用”的字节写入缓冲区。

You are seeing the correct values in the ByteBuffer. 您正在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. 缓冲区的最后一个字节的字节值为0x80,如果您在笨拙的终端中显示该符号,则将其扩展为更长的int值-128。

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: 如果仅在前面加1位,就将此带符号的字节转换为较大的类型(如int),则会看到以下内容:

1111 1111 1111 1111 1111 1111 1000 0000 

Which indicates -128 as a signed int. 表示-128为有符号int。

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

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