0

I know this may be a simple question but really i just can't solve this thing! what i want is to convert an array into a char i mean, let's suppose that someArray has into it {1,0,1,0,1,0}, and in binary, 10101010 = ª now, how can i do that? is there something like arrayToChar(byte) or something like that? my idea is to make a class with all the conversions like

if(someArray.equals(10101010)){
return "ª";
}

but i know there must be an easier an shorter way to do this, any ideas? :( please help

tasipa
  • 3
  • 1
  • 1

2 Answers2

0

The correct binary for a is 1100001. And you could do it (in Java 8+) with something like

int[] arr = { 1, 1, 0, 0, 0, 0, 1 };
StringBuilder sb = new StringBuilder();
IntStream.of(arr).forEach(x -> sb.append(x));
char ch = (char) Integer.parseInt(sb.toString(), 2);
System.out.println(ch);

or without converting to a String (and in earlier versions of Java) like

int v = 0;
for (int i = 0; i < arr.length; i++) {
    v += arr[arr.length - i - 1] * Math.pow(2, i);
}
System.out.println((char) v);

Both output (as requested)

a
Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249
0

Try this

    int[] myArray = {1, 0, 1, 0, 1, 0};
    int i = IntStream.of(myArray).reduce(0, (a, b) -> a * 2 + b);
    String s = Character.toString((char)i);
    System.out.println(Arrays.toString(myArray) + " -> " + s);
    // [1, 0, 1, 0, 1, 0] -> *