7

My byte array is look like

 byte[] x = { (byte) 0xff , (byte) 0x80  };

how can i convert it to char array {char[] y } where:-

y[0]='f';
y[1] ='f' and so on
LarsH
  • 27,481
  • 8
  • 94
  • 152
Arjun
  • 3,491
  • 4
  • 25
  • 47
  • 1
    ... and your "and so on" means what? Presumably you don't mean that every element in the array is `'f'`, which is what it looks like. – khelwood Mar 04 '15 at 12:47
  • 3
    Do you want to convert it to `{ 'f', 'f', '8', '0' }`? – Klas Lindbäck Mar 04 '15 at 12:52
  • @Thilo Why did you marked this as duplicate? The Question is about convert to char array. Convert to string is not equal convert to char array in java. Especially when it concerns the passwords. – alex Nov 08 '20 at 09:35

1 Answers1

11

This should help you:

byte[] data = { (byte) 0xff , (byte) 0x80  };
String text = new String(data, "UTF-8");
char[] chars = text.toCharArray();
BeWu
  • 1,941
  • 1
  • 16
  • 22
  • That doesn't yield `{ 'f', 'f', '8', '0' }` – Thilo Mar 04 '15 at 12:55
  • 2
    Well that wasn't specified so i assumed he wants to convert the bytes into their corresponding character values... – BeWu Mar 04 '15 at 12:57
  • True. The question was clarified later. – Thilo Mar 04 '15 at 12:58
  • Thanks Thilo for the links, sharing code worked for me . byte[] x = {(byte) 0x80,(byte) 0x60}; StringBuilder sb = new StringBuilder(x.length * 2); for(byte b: x) sb.append(String.format("%02x", b & 0xff)); String s = sb.toString(); char[] array = s.toCharArray(); – Arjun Mar 04 '15 at 13:53
  • 4
    This is unsafe for passwords. – Dávid Horváth Aug 03 '20 at 18:23