6

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'

Mohamad Ibrahim
  • 5,085
  • 9
  • 31
  • 45

4 Answers4

4

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) );
Community
  • 1
  • 1
Deco
  • 3,261
  • 17
  • 25
3

Use String.getBytes() method.

byte []bytes="Hello".getBytes();
for(byte b:bytes)
  System.out.println(b);
Buhake Sindi
  • 87,898
  • 29
  • 167
  • 228
KV Prajapati
  • 93,659
  • 19
  • 148
  • 186
  • 1
    Works great for ASCII, but if you run into the eight-bit-half, you will have negative numbers, because the powers that be decided that bytes in Java are signed. – Thilo Nov 28 '11 at 07:10
2

Hi I am not sure what do you want but may be the following method helps to print it .

    String str = "9";

    for (int i = 0; i < str.length(); i++) {
        System.out.println(str.charAt(i) + " ASCII " + (int) str.charAt(i));
    }

you can see it at http://www.java-forums.org/java-tips/5591-printing-ascii-values-characters.html

Hemant Metalia
  • 29,730
  • 18
  • 72
  • 91
1

A naive approach would be:

  1. You can iterate through a byte array:

    final byte[] bytes = "FooBar".getBytes(); for (byte b : bytes) { System.out.print(b + " "); }

    Result: 70 111 111 66 97 114

  2. or, through a char array and convert the char into primitive int

    for (final char c : "FooBar".toCharArray()) { System.out.print((int) c + " "); }

    Result: 70 111 111 66 97 114

  3. or, thanks to Java8, with a forEach through the inputSteam: "FooBar".chars().forEach(c -> System.out.print(c + " "));

    Result: 70 111 111 66 97 114

  4. or, thanks to Java8 and Apache Commons Lang: final List<Byte> list = Arrays.asList(ArrayUtils.toObject("FooBar".getBytes())); list.forEach(b -> System.out.print(b + " "));

    Result: 70 111 111 66 97 114

A better approach would use the charset (ASCII, UTF-8, ...):

// Convert a String to byte array (byte[])
final String str = "FooBar";
final byte[] arrayUtf8 = str.getBytes("UTF-8");
for(final byte b: arrayUtf8){
  System.out.println(b + " ");
}

Result: 70 111 111 66 97 114

final byte[] arrayUtf16 = str.getBytes("UTF-16BE");
  for(final byte b: arrayUtf16){
System.out.println(b);
}

Result: 70 0 111 0 111 0 66 0 97 0 114

Hope it has helped.

KeyMaker00
  • 6,194
  • 2
  • 50
  • 49