LoginSignup
35
28

More than 3 years have passed since last update.

Javaで整数 ⇄ バイト配列の相互変換

Last updated at Posted at 2015-09-17

必要なインポート

import java.nio.ByteBuffer;

整数 → 4バイトの配列

byte[] bytes = ByteBuffer.allocate(4).putInt(整数).array();

バイト配列 → 整数

int num = ByteBuffer.wrap(バイト配列).getInt();

サンプルコード

整数1695609641を4のバイトの配列に変換して、元の整数に戻す例です

import java.nio.ByteBuffer;

public class Main {

    public static void main(String[] args) {
        // int -> bytes
        byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
        // bytes -> int
        int num = ByteBuffer.wrap(bytes).getInt();

        System.out.print("bytes: ");
        for(byte b: bytes){
            System.out.printf("%x ", b);
        }
        System.out.println();

        System.out.print("int: ");
        System.out.println(num);
    }

}

出力結果

bytes: 65 10 f3 29 
int: 1695609641

参考

35
28
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
35
28