How to convert a long to a fixed-length 16-bit binary string?
java
Solution
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.)
Problem
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 0000000000000010 as ans can anyone help me ?