問題描述
我需要將數(shù)字轉(zhuǎn)換為無符號字節(jié).該數(shù)字始終小于或等于 255,因此它可以容納在一個字節(jié)中.
I need to convert a number into an unsigned byte. The number is always less than or equal to 255, and so it will fit in one byte.
我還需要將該字節(jié)轉(zhuǎn)換回該數(shù)字.我將如何在 Java 中做到這一點?我已經(jīng)嘗試了幾種方法,但都沒有奏效.這是我現(xiàn)在要做的:
I also need to convert that byte back into that number. How would I do that in Java? I've tried several ways and none work. Here's what I'm trying to do now:
int size = 5;
// Convert size int to binary
String sizeStr = Integer.toString(size);
byte binaryByte = Byte.valueOf(sizeStr);
現(xiàn)在將該字節(jié)轉(zhuǎn)換回數(shù)字:
and now to convert that byte back into the number:
Byte test = new Byte(binaryByte);
int msgSize = test.intValue();
顯然,這不起作用.由于某種原因,它總是將數(shù)字轉(zhuǎn)換為 65
.有什么建議嗎?
Clearly, this does not work. For some reason, it always converts the number into 65
. Any suggestions?
推薦答案
一個字節(jié)總是用 Java 簽名的.不過,您可以通過將其與 0xFF 進(jìn)行二進(jìn)制與運算來獲得其無符號值:
A byte is always signed in Java. You may get its unsigned value by binary-anding it with 0xFF, though:
int i = 234;
byte b = (byte) i;
System.out.println(b); // -22
int i2 = b & 0xFF;
System.out.println(i2); // 234
這篇關(guān)于如何將 Int 轉(zhuǎn)換為無符號字節(jié)并返回的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!