Bit level operations, get a little off the short value

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

This is my code and it does not make sense:

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

    }

How can I get 16 bits of an integer value?

+4
source share
4 answers

We can try this code below, we will use for the 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);
  }
+2
source

Try changing the return statement a bit:

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

    }

This will help you.

+6
source

: 16 & 0xffff.

(x & 0x8000) << 1 - , 16- 32- : , 0xffff, -1 16- , 0xffffffff, -1 32- . , , .

, ,

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

16- "" 32- , .

Note. If you are looking for a binary representation of a Stringnumber, only masking is necessary x & 0xffff, because the upper 16 bits will still be removed from the result of the string. This Q & A explains how to get a binary representation of an integer with the corresponding number of leading zeros.

+5
source

Try the following:

String.format("%16s", Integer.toBinaryString(5)).replace(' ', '0')
0
source

Source: https://habr.com/ru/post/1686206/


All Articles