1

Possible Duplicate:
Converting char array into byte array and back again

I have a password in char[] and i want this password in byte[] without creating any String. Please suggest the best possible way.

Community
  • 1
  • 1
rbhawsar
  • 805
  • 7
  • 25
  • 1
    Welcome to Stack Overflow! We encourage you to [research your questions](http://stackoverflow.com/questions/how-to-ask). If you've [tried something already](http://whathaveyoutried.com/), please add it to the question - if not, research and attempt your question first, and then come back. –  Oct 18 '12 at 08:31
  • Have you tried to [search existing questions](http://stackoverflow.com/search?tab=relevance&q=[java]%20%2bchar[]%20%2bbyte[])? – assylias Oct 18 '12 at 08:33
  • Could you please explain why you don't want any `String`s involved? –  Oct 18 '12 at 08:36
  • i did google. but not found anyuseful. – rbhawsar Oct 18 '12 at 08:38
  • @Tichodroma its a password in char[] if i convert this to string it will be there in memory but if its byte[] or char[] i can clear it up as soon as my work is done. – rbhawsar Oct 18 '12 at 08:41

2 Answers2

6

If ASCII or ISO-8859-1 encoding is all you need you can copy one char at a time.

char[] chars = ...
byte[] bytes = new byte[chars.length];
for(int i = 0; i < chars.length; i++)
    bytes[i] = (byte) chars[i];
Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

I don't know about any build in tool to do that. You may want to create a utility class that solve the issue for you.

public static byte[] charToByte(char[] array) {

  byte[] result = new byte[array.length];

  for(int i = 0; i < array.length; i++) {
    result[i] = (byte) array[i];
  }

  return result;
}

How ever this solution is limited by encoding you are using.

splungebob
  • 5,357
  • 2
  • 22
  • 45