有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从C#迁移到Java、int和ushort(按位和)

我得到了一段用C语言编写的代码,我必须迁移到Java。在C#中,代码归结为:

int foo = getFooValue();
UInt16 bar = 0x0080;
if((foo & bar) == 0)
{
  doSomeCoolStuff()
} 

既然java没有无符号数字类型,我该如何在java中做到这一点


共 (1) 个答案

  1. # 1 楼答案

    您不必担心unsigned类型,因为0x0080(十进制128)绝对填充了short,其最大值为32767

    public static void main(String[] args)
    {
        short flag = 0x0080;
    
        int foo1 = 128; // 0x00000080
    
        if ((foo1 & flag) == 0)
            System.out.println("Hit 1!");
    
        int foo2 = 0; // 0x00000000
    
        if ((foo2 & flag) == 0)
            System.out.println("Hit 2!");
    
        int foo3 = 27698; // 0x00006C32
    
        if ((foo3 & flag) == 0)
            System.out.println("Hit 3!");
    }
    
    // Output: Hit 2! Hit 3!