注意我觉得下面的公式说明的不是很详细,第一我们要转换的数目前是byte类型,因为其值范围为-128-127
因此,我们首先要将字节数转换成整型或者short短整型,然后依据下面的公式进行判断,其原理也是依据补码的原理,每位取反,末位加1,因为
一个负数的对应正数就是这样计算出来的。
这里加上我的注解,不知道对不对
byte tb = 13
int unsignedByte1 = (int)tb;
short unsignedByte2 = (int)tb;
- int unsignedByte1 = signedByte1 >= 0 ? signedByte1 : 256 + signedByte1;
short unsignedByte2 = signedByte2 <0 ? 256 + signedByte2: signedByte2 ; - byte b= (byte) (unsignedByte1 & 0xFF)
- byte c = (byte)(unsignedByte2 & 0xFF)
Casting from an int to a byte for that matter, casting from any wider integer type to a narrower typetakes place through truncation of the high-order bytes. This means that as long as the value of the wider type can be expressed in the narrower type, the value is not changed. The int 127 cast to a byte still retains the value 127.
On the other hand, if the int value is too large for a byte, strange things happen. The int 128 cast to a byte is not 127, the nearest byte value. Instead, it is -128. This occurs through the wonders of two's complement arithmetic. Written in hexadecimal, 128 is 0x00000080. When that int is cast to a byte, the leading zeros are truncated, leaving 0x80. In binary, this can be written as 10000000. If this were an unsigned number, 10000000 would be 128 and all would be fine, but this isn't an unsigned number. Instead, the leading bit is a sign bit, and that 1 does not indicate 27 but a minus sign. The absolute value of a negative number is found by taking the complement (changing all the 1 bits to 0 bits and vice versa) and adding 1. The complement of 10000000 is 01111111. Adding 1, you have 01111111 + 1 = 10000000 = 128 (decimal). Therefore, the byte 0x80 actually represents -128. Similar calculations show that the int 129 is cast to the byte -127, the int 130 is cast to the byte -126, the int 131 is cast to the byte -125, and so on. This continues through the int 255, which is cast to the byte -1.
in Java source code, all numbers preceded by 0x are read as hexadecimal.
When 256 is reached, the low-order bytes of the int are filled with zeros. In other words, 256 is 0x00000100. Thus, casting it to a byte produces 0, and the cycle starts over. This behavior can be reproduced algorithmically with this formula, though a cast is obviously simpler:
下面的这个公式是整数对应成字节数的公式
int byteValue;
- int temp = intValue % 256;
- if ( intValue < 0) {
- byteValue = temp < -128 ? 256 + temp : temp;
- }
- else {
- byteValue = temp > 127 ? temp - 256 : temp;
- }