3 回答
TA贡献1803条经验 获得超6个赞
int):
public static int unsignedToBytes(byte b) {
return b & 0xFF;
}
public static void main(String[] args) {
System.out.println(unsignedToBytes((byte) -12));
}byteByte.MAX_VALUEshort, intlong.
TA贡献1794条经验 获得超8个赞
int i = 200; // 0000 0000 0000 0000 0000 0000 1100 1000 (200)byte b = (byte) 200;
// 1100 1000 (-56 by Java specification, 200 by convention)/*
* Will print a negative int -56 because upcasting byte to int does
* so called "sign extension" which yields those bits:
* 1111 1111 1111 1111 1111 1111 1100 1000 (-56)
*
* But you could still choose to interpret this as +200.
*/System.out.println(b); // "-56"/*
* Will print a positive int 200 because bitwise AND with 0xFF will
* zero all the 24 most significant bits that:
* a) were added during upcasting to int which took place silently
* just before evaluating the bitwise AND operator.
* So the `b & 0xFF` is equivalent with `((int) b) & 0xFF`.
* b) were set to 1s because of "sign extension" during the upcasting
*
* 1111 1111 1111 1111 1111 1111 1100 1000 (the int)
* &
* 0000 0000 0000 0000 0000 0000 1111 1111 (the 0xFF)
* =======================================
* 0000 0000 0000 0000 0000 0000 1100 1000 (200)
*/System.out.println(b & 0xFF); // "200"/*
* You would typically do this *within* the method that expected an
* unsigned byte and the advantage is you apply `0xFF` only once
* and than you use the `unsignedByte` variable in all your bitwise
* operations.
*
* You could use any integer type longer than `byte` for the `unsignedByte` variable,
* i.e. `short`, `int`, `long` and even `char`, but during bitwise operations
* it would get casted to `int` anyway.
*/void printUnsignedByte(byte b) {
int unsignedByte = b & 0xFF;
System.out.println(unsignedByte); // "200"}TA贡献1876条经验 获得超5个赞
unsignedbytebyteint
bytebyte
到/从int的转换
// From int to unsigned byteint i = 200; // some value between 0 and 255byte b = (byte) i; // 8 bits representing that value
// From unsigned byte to intbyte b = 123; // 8 bits representing a value between 0 and 255int i = b & 0xFF; // an int representing the same value
Byte.toUnsignedInt.)
解析/格式化
// Parse an unsigned bytebyte b = (byte) Integer.parseInt("200");// Print an unsigned byteSystem.out.println("Value of my unsigned byte: " + (b & 0xFF));算术
// two unsigned bytesbyte b1 = (byte) 200;byte b2 = (byte) 15;byte sum = (byte) (b1 + b2); // 215byte diff = (byte) (b1 - b2); // 185byte prod = (byte) (b2 * b2); // 225
byte ratio = (byte) ((b1 & 0xFF) / (b2 & 0xFF));
添加回答
举报
