简体   繁体   English

Java 24位数字签名

[英]Java 24-bit number signing

I'm currently doing some work that has me working with some 24-bit integers. 我正在做一些让我使用一些24位整数的工作。

Essentially I need to be able to get both the signed, and unsigned values from these 24-bits. 本质上,我需要能够从这些24位获得有符号和无符号值。

Currently I'm using the following code to put the three bytes together and return me their value. 目前我正在使用以下代码将三个字节放在一起并返回其值。

private static int bytesToInt(byte[] input) {
    if (input.length == 3) {
        return (input[2] & 0xFF) << 16 | (input[1] & 0xFF) <<8 | (input[0] & 0xFF);
    }
}

The input I'm giving it are the bytes: 0x42 0x87 0xfe and the returned result is: 16680770 我给它的输入是字节: 0x42 0x87 0xfe ,返回的结果是: 16680770

This (I believe) is the correct unsigned value, however I also need the signed value of it, which I think is -96446 这(我相信)是正确的无符号值,但是我还需要它的有符号值,我认为是-96446

I'm guessing I'll have to do some bitshifting here to solve it, but I'm not sure how to accomplish this. 我猜我必须在这里做一些位移来解决它,但我不知道如何实现这一目标。

I've tried casting the result into an and a long, but neither return the signed value. 我已经尝试将结果转换为a和long,但都没有返回签名值。 I've also tried Math.abs(result), but I don't think I'm using that correctly. 我也尝试过Math.abs(结果),但我认为我没有正确使用它。

Any input would be appreciated. 任何输入将不胜感激。

Thanks 谢谢

private static int bytesToUInt(byte[] input) {
    if (input.length == 3) {
        return (input[2] & 0xFF) << 16 | (input[1] & 0xFF) <<8 | (input[0] & 0xFF);
    }
}
private static int bytesToSInt(byte[] input) {
    if (input.length == 3) {
        return (input[2]) << 16 | (input[1] & 0xFF) <<8 | (input[0] & 0xFF);
    }
}

One option is just to fill the top 8 bits with 1: 一个选项是用1填充前8位:

int x = 16680770;
int y = x | 0xff000000;
System.out.println(y); // -96446

Or you can just subtract 1 << 24 : 或者你可以减去1 << 24

int y = x - (1 << 24);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM