Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Forming a pattern of bits from a integer

Tags:

java

algorithm

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
like image 759
Ashutosh Singh Avatar asked Apr 06 '19 10:04

Ashutosh Singh


People also ask

What is a bit pattern?

A specific layout of binary digits.

How many patterns can be formed with a single bit?

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.

How do you set all bits of a number?

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.


1 Answers

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);

  }
}
like image 110
rplantiko Avatar answered Oct 19 '22 18:10

rplantiko