문제

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?

도움이 되었습니까?

해결책

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

This should work.

다른 팁

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top