Andrew Roth
Andrew Roth

Reputation: 1073

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?

Upvotes: 0

Views: 267

Answers (1)

Tommaso Belluzzo
Tommaso Belluzzo

Reputation: 23685

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!

Upvotes: 1

Related Questions