Creating a byte from an integer

非 Y 不嫁゛ 提交于 2019-12-25 02:26:45

问题


I want to create a byte using an integer. For example I have an integer of 4, I want to create a byte with a value of 4. When I do something like

byte test = 134;

I get an byte value of -122 wheras I want a byte value of simply 134 so that i can convert this to ascii later on.

I am unsure of how to achieve this but would welcome any help that can be provided. Thanks.


回答1:


In Java bytes are interpreted as signed (along with ints, shorts, and longs). The unsigned byte value of 134 is bit-equivalent to the signed byte value of -122. If you wish to use the unsigned value of a byte, you can do so by storing this value in a signed integer with more than 8 bits, such as an int:

byte test = (byte) 134;
int unsignedByteValue = ((int) test) & 0xff;
// now unsignedByteValue == 134

The bitmask of 0xff ensures that only the lower 8 bits of unsignedByteValue are ones. Otherwise, a negative signed byte would result in a negative signed int by sign extension.




回答2:


In Java, all bytes are signed. They have a value from -128 to 127. If you print out the byte, that's all you will get.

But Java has a different type for characters. You should use this instead:

char test = 134;

The char type is unsigned and will accommodate characters with numeric values up to 65,535.



来源:https://stackoverflow.com/questions/21246786/creating-a-byte-from-an-integer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!