如何将长整数转换为固定长度的16位二进制字符串? [英] How to convert a long to a fixed-length 16-bit binary string?
问题描述
我想将长整数转换为二进制,但是问题是我希望转换后得到固定的16位二进制结果,例如如果我将2转换为16位二进制,它应该给我0000000000000010,因为有人可以帮助我吗?>
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 ?
推荐答案
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);
这里的想法是通过在值的第17位放置1来获得零填充,然后使用 String.substring()
截断由此创建的前导1,因此始终给您精确的16位二进制数字.(当然,只有在您确定输入是16位数字时,此方法才起作用.)
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.)
这篇关于如何将长整数转换为固定长度的16位二进制字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!