【SINC】Unsigned

1、简介

  在本项目在开发中,后台服务器是使用C++开发的,在通信协议中使用了无符号类型,uint8,uint16,uint32。而Jdk1.6 尚不支持无符号类型。恰巧在看JAVA NIO的时候,发现《OReilly.Java.NIO》这本书在2.4.5中提供了一个存取无符号类型的工具类。

2、代码

import java.nio.ByteBuffer;

public class Unsigned {
    
    public static short getUnsignedByte(ByteBuffer bb) {
        return ((short) (bb.get() & 0xff));
    }

    public static void putUnsignedByte(ByteBuffer bb, int value) {
        bb.put((byte) (value & 0xff));
    }

    public static short getUnsignedByte(ByteBuffer bb, int position) {
        return ((short) (bb.get(position) & (short) 0xff));
    }

    public static void putUnsignedByte(ByteBuffer bb, int position, int value) {
        bb.put(position, (byte) (value & 0xff));
    }

    public static int getUnsignedShort(ByteBuffer bb) {
        return (bb.getShort() & 0xffff);
    }

    public static void putUnsignedShort(ByteBuffer bb, int value) {
        bb.putShort((short) (value & 0xffff));
    }

    public static int getUnsignedShort(ByteBuffer bb, int position) {
        return (bb.getShort(position) & 0xffff);
    }

    public static void putUnsignedShort(ByteBuffer bb, int position, int value) {
        bb.putShort(position, (short) (value & 0xffff));
    }

    public static long getUnsignedInt(ByteBuffer bb) {
        return ((long) bb.getInt() & 0xffffffffL);
    }

    public static void putUnsignedInt(ByteBuffer bb, long value) {
        bb.putInt((int) (value & 0xffffffffL));
    }

    public static long getUnsignedInt(ByteBuffer bb, int position) {
        return ((long) bb.getInt(position) & 0xffffffffL);
    }

    public static void putUnsignedInt(ByteBuffer bb, int position, long value) {
        bb.putInt(position, (int) (value & 0xffffffffL));
    }
}

3、后记

  在Java端的协议中,uint8需要使用short来保存,uint16需要使用int来保存,uint32需要使用long来保存。然后在协议传输中,使用上述工具类写入字节。

原文地址:https://www.cnblogs.com/onliny/p/2642431.html