codingthings

byte数组和int互转

import java.nio.ByteBuffer;

public class Program
{
    public static void main(String[] args)
    {
        ByteBuffer buf = ByteBuffer.allocate(3);

        writeInt24(-113, buf);
        buf.flip();
        int i1 = readInt24(buf);

        buf.clear();
        writeInt24(9408399, buf);
        buf.flip();
        int i2 = readUnsigedInt24(buf);//readInt24(buf);

        System.out.println("i1 = " + i1);
        System.out.println("i2 = " + i2);
    }

    static void writeInt24(int val, ByteBuffer buf)
    {
        buf.put((byte)(val >> 16));
        buf.put((byte)(val >> 8));
        buf.put((byte)val);
    }

    static int readInt24(ByteBuffer buf)
    {
        byte[] data = new byte[3];
        for (int i = 0; i < 3; ++i)
            data[i] = buf.get();

        return (data[0] << 16)
                | (data[1] << 8 & 0xFF00)
                | (data[2] & 0xFF);// Java总是把byte当做有符号处理;我们可以通过将其和0xFF进行二进制与来得到有符号的整型
    }

    static int readUnsigedInt24(ByteBuffer buf)
    {
        byte[] data = new byte[3];
        for (int i = 0; i < 3; ++i)
            data[i] = buf.get();

        return (data[0] << 16 & 0xFF0000)
                | (data[1] << 8 & 0xFF00)
                | (data[0] & 0xFF);
    }
}

 

发表于 2015-06-18 11:39  新叶  阅读(608)  评论(0编辑  收藏  举报
 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2022-01-29
  • 2021-12-19
  • 2021-05-24
  • 2021-08-10
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2022-02-06
  • 2021-11-28
  • 2021-08-31
  • 2022-12-23
  • 2021-11-28
  • 2021-12-10
  • 2022-01-06
相关资源
相似解决方案