0

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?

8
  • 3
    You can just use int in this particular case (even though it's signed). Commented Jan 2, 2018 at 23:07
  • 1
    @KlitosKyriacou is right. The idea of unsigned int is that it allows you to fit positive values to double the normal int value (namely 65535 for uint16). However, in this case your value is 128 which definitely fits normal int16 Commented Jan 2, 2018 at 23:15
  • 3
    And since the constant bar is defined in hex and used only for logical operation, it does not matter even if the value falls under negative zone. Commented Jan 2, 2018 at 23:28
  • 1
    @ZakiAnwarHamdani It actually does, because it is being compared to an int. The signed negative short will expand with two bytes of ones on the left, while the unsigned will expand with zeros. Commented Jan 3, 2018 at 0:11
  • 1
    Why even use any "narrow" type? You can use an int in both C# and Java. Commented Jan 3, 2018 at 0:21

1 Answer 1

1

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!
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.