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

前端 未结 8 1019
谎友^
谎友^ 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 18:01

    Most likely what you want is Integer.toBinaryString(), combined with something to ensure that you get exactly 16 places:

    int val = 2;
    String bin = Integer.toBinaryString(0x10000 | val).substring(1);
    

    The idea here is to get the zero padding by putting a 1 in the 17th place of your value, and then use String.substring() to chop off the leading 1 this creates, thus always giving you exactly 16 binary digits. (This works, of course, only when you are certain that the input is a 16-bit number.)

提交回复
热议问题