• 【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来保存。然后在协议传输中,使用上述工具类写入字节。

  • 相关阅读:
    《jQuery实战(第二版)》读书笔记
    软件测试对于代码安全的诸多事宜
    关于Maven的安装及初步使用
    Windows下GIT安装与使用(上传远程端)
    白盒测试
    关于VS2013的编码的UI测试。
    闰年检验
    等价类划分例子中的些许添加
    软件测试技术第二周课堂等价类习题
    软件测试技术第一周课堂随笔记录
  • 原文地址:https://www.cnblogs.com/onliny/p/2642431.html
Copyright © 2020-2023  润新知