0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Java】byte配列を16進数にしたい

Posted at

やりたいこと

文字コード“あ”をUTF-16にしたい

期待する結果

10進数:48(10) 46(10)
16進数:30(16) 42(16)

実現方法

String.FormatSystem.out.printf を使う

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String stringValue = "あ";
        byte [] mojiCode = stringValue.getBytes(StandardCharsets.UTF_16BE);
        System.out.println(mojiCode);        //[B@372f7a8d
        System.out.println(  Arrays.toString(mojiCode)); //[48, 66]
        for (Byte code : mojiCode) {
            System.out.printf("%02x", code); //3042
        }
        System.out.println("");
        StringByteArray stringByteArray = new StringByteArray(mojiCode);
        System.out.println(stringByteArray.toHexString()); //3042
    }
    static class StringByteArray {
        byte[] byteArray;
        public StringByteArray(byte[] byteArray) {
            this.byteArray = byteArray;
        }
        public String toHexString() {
            StringBuffer stringBuffer = new StringBuffer();
            for (byte code : byteArray) {
                String hexString = String.format("%02x", code);
                stringBuffer.append(hexString);
            }
            return stringBuffer.toString();
        }
    }
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?