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

前端 未结 8 1016
谎友^
谎友^ 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.)

    0 讨论(0)
  • 2020-12-10 18:04

    I'm presuming that you want a String output of fixed length (16). Here's what the code would look like:

    String binarized = Integer.toBinaryString(i);
    int len = binarized.length();
    String sixteenZeroes = "00000000000000000";
    if (len < 16)
      binarized = sixteenZeroes.subString(0, 16-len).concat(binarized);
    else
      binarized = binarized.subString(len - 16);
    return binarized;
    

    Warning: I didn't compile or run it, so make sure no bug is there :)

    0 讨论(0)
提交回复
热议问题