Reputation: 85
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?
Upvotes: 0
Views: 2571
Reputation: 21
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
Upvotes: 0
Reputation: 1787
How about this?
int output=0;
for(int i=0;i<u.length();i++)
output=output<<1|u[i]-'a';
Upvotes: 1
Reputation: 2812
int num = 0;
for(char c : u) {
num = (num << 1) + (c - 'a');
}
This should work.
Upvotes: 1