Skip to content

Instantly share code, notes, and snippets.

@hrgdavor
Last active April 25, 2017 16:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hrgdavor/715ce0906405727b499808d20494b2c9 to your computer and use it in GitHub Desktop.
Save hrgdavor/715ce0906405727b499808d20494b2c9 to your computer and use it in GitHub Desktop.
java convert long to 64 bits(0|1) string
public class Bits{
public static void main(String[] args){
long val = -12435L;
System.out.println(longBits(val));
// 1111111111111111111111111111111111111111111111111100111101101101
System.out.println(longBitsSpaced(val));
// 11111111 11111111 11111111 11111111 11111111 11111111 11001111 01101101
}
public static String longBits(long val) {
StringBuffer b = new StringBuffer(64);// 64 bits
for(int i=63;i>=0; i--) {
b.append((val & (1L<<i)) == 0 ? '0':'1');
}
return b.toString();
}
public static String longBitsSpaced(long val) {
StringBuffer b = new StringBuffer(71);// 64 bits + 7 spaces
for(int i=63;i>=0; i--) {
b.append((val & (1L<<i)) == 0 ? '0':'1');
if(i>0 && i%8 ==0) b.append(' ');
}
return b.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment