Question

Consider the following character array

char[] u = {'a', 'b', 'b', 'a' };

I am looking for the most time efficient way in to convert it to a binary string (of the kind 0110) since I need to do some bit shifting and counts on the array in an efficient manner. The array above would be translated to an integer value 6, binary 0110.

I've used a converting to a new string, and then do two replace calls on it, before converting it to an integer with radix 2 but it doesn't look like an efficient way to me.

Any help?

Was it helpful?

Solution

int num = 0;
for(char c : u) {
    num = (num << 1) + (c - 'a');
}

This should work.

OTHER TIPS

How about this?

int output=0;
for(int i=0;i<u.length();i++)
    output=output<<1|u[i]-'a';

try this

char[] u = {'a', 'b', 'b', 'a' };
 for(int i=0;i<u.length;i++){
  int y = (int)u[i];
  System.out.println(Integer.toBinaryString(y));}

hope it helps

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top