0

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?

3
  • How do you know 00000001 is just {'b'} and not {'a'a'a'a'a'b} Commented Mar 21, 2014 at 14:50
  • Same way you know 1 is 000000001. Commented Mar 21, 2014 at 14:52
  • Cause I know the length of the original char array,as U Mad said. Commented Mar 21, 2014 at 18:18

3 Answers 3

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

This should work.

Sign up to request clarification or add additional context in comments.

Comments

1

How about this?

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

2 Comments

This wouldn't compile as u is a char array, not a string. If it was a string it still wouldn't compile since the correct method is charAt not getCharAt.
Oh I'm sorry, I forgot that. Just replace u.getCharAt(i) for u[i].
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.