How to convert a long to a fixed-length 16-bit binary string?

前端 未结 8 1046
谎友^
谎友^ 2020-12-10 17:23

Hi i want to convert a long integer to binary but the problem is i want a fixed 16 bit binary result after conversion like if i convert 2 to 16 bit binary it should give me

8条回答
  •  没有蜡笔的小新
    2020-12-10 17:43

    In contrast to many suggestions here: Integer.toBinaryString, doesn't work for a 16 bit (a short) and it will not print leading zero's. The reason is that (as the name suggests) this will only work for integers. And for negative numbers the bit representation will change (the first bit indicates a negative number). The two numbers below represent the same number in short and int. So if you want to represent the raw bits you have received (this is the general application of your problem), this function will generate strange output.

    decimal: -3
    short:                     1111 1111 1111 1101
    int:   1111 1111 1111 1111 1111 1111 1111 1101
    

    EDIT: Changed the number above

    Hence you can not cast the short if you are interested in the bit.

    Java doesn't provide the implementation for short, so you will have to provide your own. Something like this (size is the number of bits):

    int displayMask = 1 << (size - 1);
    StringBuffer buf = new StringBuffer( size);
    for ( int c = 1; c <= size; c++ ) 
    {
        buf.append( ( value & displayMask ) == 0 ? '0' : '1' );
        value <<= 1;
    }
    

提交回复
热议问题