码迷,mamicode.com
首页 > 编程语言 > 详细

byte数组和int互转

时间:2015-06-18 12:56:20      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

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

 

byte数组和int互转

标签:

原文地址:http://www.cnblogs.com/codingthings/p/4585434.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!