2011-11-28 4 views
4

누군가가 문자열 즉, 해당 ASCII 코드로 인쇄하는 방법을 말해 줄 수 있습니까?!인쇄 문자열을 바이트로

내 입력은 「9」등 정상적인 문자열로 출력 문자의 ASCII 값에 대응되어야 '9'

답변

3

String.getBytes() 사용 방법. 내가 아니라고

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)); 
+1

ASCII에서는 훌륭하게 작동하지만 8 비트 반으로 실행하면 음수가됩니다. 자바에서 바이트로 결정된 힘이 서명되기 때문입니다. – Thilo

1

에서 그것을 볼 수 있습니다 :

  1. 당신은 바이트 배열을 반복 할 수

    :

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

    결과 : 70 111 111 66 97 114

  2. 또는 문자 배열을 통해 원시적 INT

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

    결과로 숯 변환 : 70 111 111 66 97 114

  3. 또는 Java8 덕분에 forEach를 통해 InputSteam을 통해 : "FooBar".chars().forEach(c -> System.out.print(c + " "));

    012 3,516,

    결과 : 70 111 111 66 97 114

  4. 또는 Java8 덕분 및 Apache Commons Lang : final List<Byte> list = Arrays.asList(ArrayUtils.toObject("FooBar".getBytes())); list.forEach(b -> System.out.print(b + " "));

    결과 : 70 111 111 66 97 114

더 나은 방법은 0을 사용하는 것입니다.(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 + " "); 
} 

결과 : 70 111 111 66 97 114

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

결과 : 70 0 111 0 111 0 66 0 97 0 114

희망 도움이되었습니다.

관련 문제