Skip to content

Instantly share code, notes, and snippets.

@kwonghung-YIP
Last active May 17, 2022 01:19
Show Gist options
  • Save kwonghung-YIP/f2d19fe62309b378b5338ded9fa36a47 to your computer and use it in GitHub Desktop.
Save kwonghung-YIP/f2d19fe62309b378b5338ded9fa36a47 to your computer and use it in GitHub Desktop.
Find the binary string of a long value with bitwise operator (Java)
// "static void main" must be defined in a public class.
public class Main {
public static void main(String[] args) {
listItem(new String[] {"A","B","C","D","E","F"});
}
static public void listItem(String[] names) {
int n = names.length;
for (int c=0;c<Math.pow(2,n);c++) {
System.out.print("{");
boolean firstItem = true;
for (int i=0;i<n;i++) {
if (((c>>i)&1)==1) {
System.out.print((firstItem?"":",")+names[i]);
firstItem = false;
}
}
System.out.println("}");
}
}
}
public class MyClass {
public static void main(String args[]) {
int noOfBit = 9;
long mlb = (long)Math.pow(2,noOfBit-1);
for (long l=0;l<Math.pow(2,noOfBit);l++) {
for (int b=0;b<noOfBit-1;b++) {
System.out.print(((l<<b)&mlb)==mlb?1:0);
}
System.out.print(((l<<(noOfBit-1))&mlb)==mlb?1:0);
System.out.println(":"+l);
}
}
}
public class MyClass {
public static void main(String args[]) {
int zero = '0'; //ascii code for character '0'
//char c = (char)a;
int noOfBit = 9;
char[] binaryString = new char[noOfBit];
for (int l=0;l<Math.pow(2,noOfBit);l++) {
for (int b=0;b<noOfBit;b++) {
//binaryString[noOfBit-b-1] = ((l>>b)&1)==1?'1':'0';
binaryString[noOfBit-b-1] = (char)(((l>>b)&1)+zero);
}
System.out.println(new String(binaryString)+":"+l);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment