我有一个int型数据  比如2012,现在想把它放到十六进制byte中存储。使用了Integer.toHexString(2012);变为了十六进制的字符“7dc”,我想知道怎么样能把7dc变为byte型的0x07,0xdc呢?谢谢

解决方案 »

  1.   

    先转为字符串,然后再按照char逐个变为十六进制。String str = String.valueOf(2012);
    char[] cs = str.toCharArray();
    for (char c:cs) {
      System.out.println(Integer.toHexString(12));
    }
      

  2.   

    发现理解错你的意思,你只是需要将int转储为byte[]:        int a = 2012;
            byte[] bs = new byte[2];
            bs[0] = (byte) (a & 0xff);
            bs[1] = (byte) ((a >> 8) & 0xff);
      

  3.   

    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);
    }
      

  4.   

    0xdc 在 byte 中,就是 -36你要得到发送出去的数据是什么形态的:字符串?还是byte数组?
      

  5.   

    byte数组   怎么可以是0xdc呢?
      

  6.   

    0xdc 是书写格式(写源码让编译器能识别),不是真实的内存存储形态。你可以自己试试看:
      byte[] bs = {(byte)0xdc, (byte)0x07};
      System.out.println(bs[0]);
      System.out.println(bs[1]);
      

  7.   

    String hexstr = "0x1d";
    byte[0] = Integer.parseInt(hexstr, 16);
      

  8.   

    //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;
    }
    }