Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print String as Bytes

Can somebody tell me how to print a string as bytes i.e. its corresponding ASCII code?!

My input is a normal string like "9" and the output should be the corresponding ASCII value of character '9'

like image 975
Mohamad Ibrahim Avatar asked Nov 28 '11 06:11

Mohamad Ibrahim


2 Answers

If you're looking for a Byte Array - see this question: How to convert a Java String to an ASCII byte array?

To get the ascii value of each individual character you can do:

String s = "Some string here";

for (int i=0; i<s.length();i++)
  System.out.println("ASCII value of: "+s.charAt(i) + " is:"+ (int)s.charAt(i) );
like image 83
Deco Avatar answered Oct 12 '22 14:10

Deco


Use String.getBytes() method.

byte []bytes="Hello".getBytes();
for(byte b:bytes)
  System.out.println(b);
like image 22
KV Prajapati Avatar answered Oct 12 '22 14:10

KV Prajapati