Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
27
Help us understand the problem. What are the problem?

More than 1 year has passed since last update.

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

必要なインポート

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

参考

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
27
Help us understand the problem. What are the problem?