5

I'm trying to get the following result 00000000000000101 from this input 5.

This my code and it doesn't make sense:

public static int get16Bits(int x)
    {
        System.out.println((x & 0xffff) - ((x & 0x8000) << 1));
        return (x & 0xffff) - ((x & 0x8000) << 1);

    }

How i can get the 16bits of integer value?

  • Which *16bits* do you mean? Your question doesn't seem to make much sense. `00000000000000101` is just the binary representation of `5` with some leading zeros. So for this example input your method should just return the input as far as I guess. – SpaceTrucker Sep 22 '17 at 12:49
  • Try this: `String.format("%016d", Integer.parseInt(Integer.toBinaryString(x)))` – Procrastinator Sep 22 '17 at 12:50
  • @procrastinator This is what he wants? Nice, if you guessed correctly you should post an answer, I will upvote. – Oleg Sep 22 '17 at 12:51
  • @SpaceTrucker yup, i need the 16 bits binary. –  Sep 22 '17 at 12:52
  • @Oleg that's what I understood from the problem. Ain't sure whether they meant the same or different. – Procrastinator Sep 22 '17 at 12:53

4 Answers4

8

Try changing your return statement a bit:

    public static String get16Bits(int x)
    {
        return (String.format("%016d", Integer.parseInt(Integer.toBinaryString(x))));

    }

This should help you.

Procrastinator
  • 2,526
  • 30
  • 27
  • 36
6

The first part is self-explanatory: the upper 16 bits are removed with & 0xffff masking.

Subtracting (x & 0x8000) << 1 is a trick that keeps the proper sign of the 16-bit number in the 32-bit result: for example, 0xffff, a -1 in 16-bit representation, gets converted to 0xffffffff, which is also -1 in 32-bit representation. This is better than using a conditional, because it is branch-free.

Another trick that you could use is

(((x & 0xFFFF) << 16) >> 16)

This lets the sign bit of 16-bit number "touch" the sign bit of 32-bit number, letting the right shift to sign-extend the result.

Note: If you are looking for a binary String representation of the number, only x & 0xffff masking is necessary, because the upper 16 bits are dropped from the string result anyway. This Q&A explains how to obtain a binary representation of an integer with the appropriate number of leading zeros.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

We can try this code below, we will use for loop :

public void getBits(int number){

      String bits = "";
      for (int i = 0; i < 16; i++) {
          bits = (number & 1) + bits;
          number >>= 1;
      }
      System.out.println("The bits are " + bits);
  }
0

Try below :

String.format("%16s", Integer.toBinaryString(5)).replace(' ', '0')
Raju Sharma
  • 2,496
  • 3
  • 23
  • 41