Java整数到字节数组 [英] Java integer to byte array

查看:31
本文介绍了Java整数到字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我得到一个整数:1695609641

当我使用方法时:

String hex = Integer.toHexString(1695609641);system.out.println(hex);

给出:

6510f329

但我想要一个字节数组:

byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};

我该怎么做?

解决方案

使用 Java NIO 的 ByteBuffer 很简单:

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();对于(字节 b :字节){System.out.format("0x%x", b);}

输出:

<前>0x65 0x10 0xf3 0x29

I got an integer: 1695609641

when I use method:

String hex = Integer.toHexString(1695609641);
system.out.println(hex); 

gives:

6510f329

but I want a byte array:

byte[] bytearray = new byte[] { (byte) 0x65, (byte)0x10, (byte)0xf3, (byte)0x29};

How can I make this?

解决方案

using Java NIO's ByteBuffer is very simple:

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

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

output:

0x65 0x10 0xf3 0x29 

这篇关于Java整数到字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆