I need help to design java code for generating bit array for any given integer in following manner:
23 should produce output as 1101011 (min length array)
explaination :
positions are given as 1 -2 4 -8 16 -32 ....
So 1101011 can be evaluated as:
1*1 + 1*-2 + 0*4+ 1*-8 + 0*16 +1*-32 + 1*64 = 23
                A specific layout of binary digits.
A 1-bit image can have 2 colours, a 4-bit image can have 16, an 8-bit image can have 256, and a 16-bit image can have 65,536.
Setting all bits can be done by using the | (OR) bit operator with 1s for each of the bits. This is because 1 OR with any number sets the number as 1.
This is the so-called negabinary representation of numbers (described first by Vittorio Grünwald in 1885). They can be encoded in a fashion very similar to the usual binary representation, just working with -2 instead of 2 as base (Java code inspired by C# code on https://en.wikipedia.org/wiki/Negative_base ):
class EncodeNegaBinary {
  public static void main(String[] args) {
    int n=0,input=0;
    String result="";
    final String[] BITS = { "0","1" };
    if (args.length != 1) {
      System.err.println("Please enter an integer to be converted");
      return;
    } else {
      input = n = Integer.parseInt(args[0]);
    }
    while (n != 0) {
      int r = n%-2;
      n /= -2;
      if (r == -1) {
        r=1;
        n++;
      }
      result = BITS[r] + result;
    }
    System.out.printf( "%d -> %s\n", input, result);
  }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With