简体   繁体   中英

Migrating from C# to Java, int & ushort (Bitwise AND)

I've been given a section of code written in C# that I have to migrate to Java. In C#, the code boils down to:

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

Given that java doesn't have unsigned number types, how do I do this in Java?

You don't have to worry about the unsigned type since 0x0080 (decimal 128 ) absolutely fills a short , whose maximum value is 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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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