Last active
April 25, 2017 16:48
-
-
Save hrgdavor/715ce0906405727b499808d20494b2c9 to your computer and use it in GitHub Desktop.
java convert long to 64 bits(0|1) string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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