int怎么转换为byte数组 java

将 int 转换为字节数组可以通过以下步骤实现:创建一个 ByteBuffer 对象将 int 值写入 ByteBuffer获取 ByteBuffer 中的字节数组

int 转换为字节数组

如何将 int 转换为字节数组?

要将 int 转换为字节数组,可以使用以下步骤:

Java 代码:

import java.nio.ByteBuffer;

public class IntToByteArray {

    public static void main(String[] args) {
        // 要转换的 int 值
        int value = 12345;

  

// 创建一个 ByteBuffer 对象 ByteBuffer buffer = ByteBuffer.allocate(4); // 将 int 值写入 ByteBuffer buffer.putInt(value); // 获取 ByteBuffer 中的字节数组 byte[] bytes = buffer.array(); // 打印字节数组 for (byte b : bytes) { System.out.println(b); } } }

说明:

  • ByteBuffer 类提供了将基本类型转换为字节数组的方法。
  • ByteBuffer.putInt(value) 方法将给定的 int 值写入 ByteBuffer。
  • ByteBuffer.array() 方法返回包含 ByteBuffer 中所有字节的数组。

示例:

如果要将 int 值 12345 转换为字节数组,输出将为:

17
-126
73
-128

这四个字节分别表示 12345 的二进制补码表示:

17: 00010001
-126: 11111110
73: 01001001
-128: 10000000