Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Byte String to alpha-numeric char array in java?

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.

like image 373
user1619114 Avatar asked Feb 13 '26 08:02

user1619114


1 Answers

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"
}
like image 163
Y__ Avatar answered Feb 14 '26 22:02

Y__



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!