简体   繁体   English

获取Java int的低16位作为有符号的16位值

[英]getting the bottom 16 bits of a Java int as a signed 16-bit value

Hmmm. Consider this program, whose goal is to figure out the best way to get the bottom 16 bits of an integer, as a signed integer. 考虑一下该程序,其目标是找出获取整数的低16位(作为有符号整数)的最佳方法。

public class SignExtend16 {
    public static int get16Bits(int x)
    { 
        return (x & 0xffff) - ((x & 0x8000) << 1);
    }

    public static int get16Bits0(int x)
    { 
        return (int)(short)(x);
    }    

    public static void main(String[] args)
    {
        for (String s : args)
        {
            int x = Integer.parseInt(s);
            System.out.printf("%08x => %08x, %08x\n",
               x, get16Bits0(x), get16Bits(x));
        }
    }
}

I was going to use the code in get16Bits0, but I got the warning "Unnecessary cast from short to int" with Eclipse's compiler and it makes me suspicious, thinking the compiler could optimize out my "unnecessary cast". 我本打算使用get16Bits0中的代码,但是在Eclipse的编译器中收到警告“从short到int不必要的转换”,这让我感到怀疑,认为编译器可以优化我的“不必要的转换”。 When I run it on my machine using Eclipse's compiler, I get identical results from both functions that behave the way I intended (test arguments: 1 1111 11111 33333 66666 99999 ). 当我使用Eclipse的编译器在计算机上运行它时,我从两个函数中均得到了与我预期的行为相同的结果(测试参数:1 1111 11111 33333 66666 99999)。 Does this mean I can use get16Bits0? 这是否意味着我可以使用get16Bits0? (with suitable warnings to future code maintainers) I've always assumed that JRE and compiler behavior are both machine-independent for arithmetic, but this case is testing my faith somewhat. (向未来的代码维护人员发出适当的警告)我一直认为JRE和编译器的行为对于算术均与计算机无关,但是这种情况在某种程度上测试了我的信念。

由于数字类型转换是隐式友好的,所以我认为收到警告的唯一原因是编译器将始终在返回时将类型转换为int,从而使您的显式类型转换变得多余。

Well, first of all the warning is correct as you can always move "up" with arithmetic conversions. 好吧,首先警告是正确的,因为您总是可以通过算术转换“上移”。 Only the other way needs a cast because you might lose data (or precision for floats). 只有其他方式才需要强制转换,因为您可能会丢失数据(或浮点数的精度)。

When you reduce from int to short you have to indicate that it's intentional by using a cast. 当从int减少到short时,必须使用强制转换来表明它是有意的。 But when you convert the short value back to int there's no danger and it happens automatically. 但是,当您将short值转换回int时,没有危险,它会自动发生。

So, all you need is 所以,您需要做的就是

return (short) x;

If you wanted to avoid the cast, you could do it as: 如果要避免强制转换,则可以按照以下步骤进行:

(x << 16) >> 16

This technique also works with different numbers of bits. 此技术还适用于不同数量的位。 Say bottom 15: 说底15:

(x << 17) >> 17 (x << 17)>> 17

Change >> to >>> for unsigned version. 将>>更改为>>>,以获取未签名的版本。

是的,get16Bits0应该可以工作,只需在函数前面添加一个preventWarning元标记。

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

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