5

Is there any builtin support for outputting a binary representation of a short in java?

There is of course, this, which recommends the use of Integer.toBinaryString(), which works. There is no comparable Short.toBinaryString(). Is anything else available?

Update: Integer.toBinaryString() doesn't quite work the way Short.toBinaryString() would work if it existed.

public static void main(String[] args) {
 System.out.println(Integer.toBinaryString(Short.MIN_VALUE));
}

produces

11111111111111111000000000000000

whereas I would like to see

1000000000000000

Of course, it's easy enough to chop off the first 16 digits, but that's kind of my point. This method ought to exist.

asked Nov 20, 2013 at 21:46

1 Answer 1

9

All shorts can be safely cast to integers, so the linked answer will work fine as long as you correctly convert the short value to int before making the conversion (and in doing so, we're making sure that the digits at the beginning are zeroed):

short x = 10;
System.out.println(Integer.toBinaryString(0xFFFF & x));
=> 1010
System.out.println(Integer.toBinaryString(0xFFFF & Short.MIN_VALUE));
=> 1000000000000000

To put it another way: all shorts are integers, so there's no need to define a separate method for obtaining the binary representation of a short.

answered Nov 20, 2013 at 21:48
Sign up to request clarification or add additional context in comments.

4 Comments

@SteveCohen right you are. A bit of fiddling is required, see my updated answer
Well, with that amendment I'll call it good. There's nothing better. I wish the inventors of java hadn't been so quick to dismiss unsigneds.
@SteveCohen agreed, they did it to simplify the language, but unsigned values are useful enough and they should have been a part of the language
heh, just try interoperating with legacy C. :-) Welcome to my world.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.