[英]Turn a signed byte into an unsigned half-byte
So I have asmall problem here, and I have no clue what could be wrong.所以我在这里遇到了一个小问题,我不知道哪里出了问题。 Thats why I'm asking if this (what I'll show you now) ist correct.这就是为什么我要问这(我现在将向您展示的内容)是否正确。 I'm turning Binary Files into Byte Lists, so that I can turn those bytes into half bytes.我正在将二进制文件转换为字节列表,以便我可以将这些字节转换为半字节。 For Example: If I get 96 as decimal number (60 as hexadecimal) I want to get 6 and 0 out of it.例如:如果我得到 96 作为十进制数(60 作为十六进制),我想从中得到 6 和 0。 The same thing with 127 (hex:7F) - I want to get 7 and 15. To achieve this I wrote the following code: You'll notice, that I need "unsigned bytes" for this in order to work与 127(十六进制:7F)相同的事情 - 我想得到 7 和 15。为了实现这一点,我编写了以下代码:你会注意到,我需要“无符号字节”才能工作
System.out.println((byte) ((UnsignedByte.unsignedToBytes(b) - (UnsignedByte.unsignedToBytes(b) % 16)) / 16));
System.out.println((byte) (UnsignedByte.unsignedToBytes(b) % 16));
public static int unsignedToBytes(byte b) {
return b & 0xFF;
}
Am I doing something wrong or is this not a Problem?我做错了什么还是这不是问题?
Use bit shifting and bitwise operations:使用位移位和按位运算:
lowerNibble = wholeByte & 0x0F
要获得低四位,请使用lowerNibble = wholeByte & 0x0F
upperNibble = (wholeByte >> 4) & 0x0F
要获得高四位,请使用upperNibble = (wholeByte >> 4) & 0x0F
This disregards the sign, because the upper portion of the number is truncated off by & 0x0F
.这忽略了符号,因为数字的上部被& 0x0F
截断了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.