3

My question is, I guess, quite simple :

How to convert a Byte to alpha-numeric char array (String) in java ?

I tried this but it gives me back an error on netbeans :

 byte[] b = "test".getBytes("ASCII");
 String test = new String(b,"ASCII");

UPDATE : I am actually using this code :

    byte[] b = "test".getBytes("ASCII");
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String bla = new String(md.digest(b), "ASCII");

But once I try to use for other stuff which requires String with ASCII, I receive the following errors like "This is not ASCII". I don't really understand, actually.

When I try to print it I got something weird like "2Q�h/�k�����"

Thank you in advance for your help.

11
  • 2
    OK, that byte vs. byte[] was just a typo... What's the error you're getting? Commented Aug 27, 2012 at 13:10
  • It doesn't want to compile according to netbeans... I don't understand. When I try to print b I got this kind of result : 2Q�h/�k�����U�b=���u����(��>T� Commented Aug 27, 2012 at 13:11
  • Are you sure your original String is ASCII? Please provide an example. Commented Aug 27, 2012 at 13:11
  • works for me, what error are you getting? Commented Aug 27, 2012 at 13:12
  • 1
    No, you don't update it, you keep modifying the question. Commented Aug 27, 2012 at 13:32

2 Answers 2

1

You're close :

public static void main(String[] args) throws java.io.UnsupportedEncodingException { //you should throw or catch this exception
   byte[] b = "test".getBytes("ASCII"); // And you must declare a byte array
   String test = new String(b,"ASCII");

   System.out.println(test); // Will output "test"
}
Sign up to request clarification or add additional context in comments.

Comments

0

After your edits I think you want to generate a SHA-256 hash of a given String.

try {
    byte[] b = "test".getBytes("ASCII");
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    byte[] hashBytes = md.digest(b);
    StringBuffer hexString = new StringBuffer();
    for (int i = 0; i < hashBytes.length; i++) {
        hexString.append(Integer.toHexString(0xFF & hashBytes[i]));
    }
    System.out.println(hexString);
} catch (Exception e) {
    e.printStackTrace();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.