java 怎么将十六进制变为相同内容的byte

ysxmwyhh 2012-07-20 09:19:37
我有一个int型数据 比如2012,现在想把它放到十六进制byte中存储。使用了Integer.toHexString(2012);变为了十六进制的字符“7dc”,我想知道怎么样能把7dc变为byte型的0x07,0xdc呢?谢谢
...全文
211 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
MiceRice 2012-07-21
  • 打赏
  • 举报
回复
0xdc 是书写格式(写源码让编译器能识别),不是真实的内存存储形态。

你可以自己试试看:
byte[] bs = {(byte)0xdc, (byte)0x07};
System.out.println(bs[0]);
System.out.println(bs[1]);
linguangliang 2012-07-21
  • 打赏
  • 举报
回复
//main中测试:
System.out.println(new HexInt(2012).toHexString(true, true));
System.out.println(new HexInt(2012).toHexString(true, false));
System.out.println(new HexInt(2012).toHexString(false, true));
System.out.println(new HexInt(2012).toHexString(false, false));
//如果仅仅是简单输出,可以如下转换
int mask = 0x0000000f;
String str = "0x";
for(int value = 2012,i=7; i >= 0;--i)
str += Integer.toHexString(((value >> i*4) & mask));
System.out.println(str);


class HexInt{
private int value; //保存该int数字,可能后续会使用到
private byte[] bArr = new byte[4]; //该int数字对应的byte数组

public HexInt(int value){
this.value = value;
for(int i = 0; i < 4; ++i){
bArr[i]= (byte)(value >> (3-i)*8);
// System.out.println(i + ":" + bArr[i] + ":" + Integer.toHexString(bArr[i]));
}
}

//输出该int数字对应的16进值,prefix=true:输出前导0x,zero=true:输出前导0
//当然我们也可以在定义prefix,zero为成员变量,并在构造函数中对其赋值,这样就可以
//定义一个不带参数的toHexString,这里仅做演示,你可以自己优化
public String toHexString(boolean prefix,boolean zero){
String ret = "";
int mask = 0x0000000f;
if(prefix)
ret += "0x";
for(int i = 0; i < 4; ++i){
for(int j = 0; j < 2; ++j){
byte hilo = (byte)((bArr[i]>>(1-j)*4) & mask);
if(hilo != 0 || (0 == hilo && zero)){
ret += Integer.toHexString(hilo);
}
}

}
return ret;
}
}
linwolong 2012-07-21
  • 打赏
  • 举报
回复
String hexstr = "0x1d";
byte[0] = Integer.parseInt(hexstr, 16);
龙腾冰 2012-07-21
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

发现理解错你的意思,你只是需要将int转储为byte[]:

int a = 2012;
byte[] bs = new byte[2];
bs[0] = (byte) (a & 0xff);
bs[1] = (byte) ((a >> 8) & 0xff);
[/Quote]
很好呢
ysxmwyhh 2012-07-20
  • 打赏
  • 举报
回复
byte数组 怎么可以是0xdc呢?
MiceRice 2012-07-20
  • 打赏
  • 举报
回复
0xdc 在 byte 中,就是 -36

你要得到发送出去的数据是什么形态的:字符串?还是byte数组?
ysxmwyhh 2012-07-20
  • 打赏
  • 举报
回复
3楼的是输出的以16进制输出 但我要得到数据发送出去的呀!
ysxmwyhh 2012-07-20
  • 打赏
  • 举报
回复
2楼的方法不行呀 得到一个-36,一个7呀!
qybao 2012-07-20
  • 打赏
  • 举报
回复
for example
int n = 2012;
byte[] b = new byte[4]; //原则上,int需要4个byte,LZ只想保存低2字节也可以
for (int i=0; i<4; i++) {
b[4-i-1] = (byte)((n>>(8*i)) & 0xff);
}
for (byte bb : b) {
System.out.printf("%04x\n", bb);
}
MiceRice 2012-07-20
  • 打赏
  • 举报
回复
发现理解错你的意思,你只是需要将int转储为byte[]:

int a = 2012;
byte[] bs = new byte[2];
bs[0] = (byte) (a & 0xff);
bs[1] = (byte) ((a >> 8) & 0xff);
MiceRice 2012-07-20
  • 打赏
  • 举报
回复
先转为字符串,然后再按照char逐个变为十六进制。

String str = String.valueOf(2012);
char[] cs = str.toCharArray();
for (char c:cs) {
System.out.println(Integer.toHexString(12));
}

62,621

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧