标签:starting into pack com oid .net offset gbk int
Bits是一个工具类,用于获取bytes数组的值的。
首先先确定char的存储的字节个数:请看博客:https://www.cnblogs.com/louiswong/p/6062417.html 或者 https://www.cnblogs.com/lchzls/p/7071862.html
从上面博客中截取的截取的一段话:
char一定是两个字节吗?不是的,这个跟我们选用的字符编码有关,如果采用”ISO-8859-1”编码,那么一个char只会有一个字节。如果采用”UTF-8”或者“GB2312”、“GBK”等编码格式呢?这几种编码格式采用的是动态长度的,如果是英文字符,大家都是一个字节。如果是中文,”UTF-8”是三个字节,而”GBK”和”GB2312”是两个字节。而对于”unicode”而言,无论如何都是两个字节。
首先先确认各个类型所占有的字节数量: char-2个字节 int-4个字节 float-4个字节 long-8个字节 double-8个字节
package java.io;
/**
* 工具类
*/
class Bits {
/*
* 获取当前的boolean值 0-false 1-true
*/
static boolean getBoolean(byte[] b, int off) {
return b[off] != 0;
}
/*
* unicode char占有两个字节的时候,先获取高八位,在获取低八位
*/
static char getChar(byte[] b, int off) {
return (char) ((b[off + 1] & 0xFF) +
(b[off] << 8));
}
static short getShort(byte[] b, int off) {
return (short) ((b[off + 1] & 0xFF) +
(b[off] << 8));
}
static int getInt(byte[] b, int off) {
return ((b[off + 3] & 0xFF) ) +
((b[off + 2] & 0xFF) << 8) +
((b[off + 1] & 0xFF) << 16) +
((b[off ] ) << 24);
}
static float getFloat(byte[] b, int off) {
return Float.intBitsToFloat(getInt(b, off));
}
static long getLong(byte[] b, int off) {
return ((b[off + 7] & 0xFFL) ) +
((b[off + 6] & 0xFFL) << 8) +
((b[off + 5] & 0xFFL) << 16) +
((b[off + 4] & 0xFFL) << 24) +
((b[off + 3] & 0xFFL) << 32) +
((b[off + 2] & 0xFFL) << 40) +
((b[off + 1] & 0xFFL) << 48) +
(((long) b[off]) << 56);
}
static double getDouble(byte[] b, int off) {
return Double.longBitsToDouble(getLong(b, off));
}
/*
* Methods for packing primitive values into byte arrays starting at given
* offsets.
*/
static void putBoolean(byte[] b, int off, boolean val) {
b[off] = (byte) (val ? 1 : 0);
}
static void putChar(byte[] b, int off, char val) {
b[off + 1] = (byte) (val );
b[off ] = (byte) (val >>> 8);
}
static void putShort(byte[] b, int off, short val) {
b[off + 1] = (byte) (val );
b[off ] = (byte) (val >>> 8);
}
static void putInt(byte[] b, int off, int val) {
b[off + 3] = (byte) (val );
b[off + 2] = (byte) (val >>> 8);
b[off + 1] = (byte) (val >>> 16);
b[off ] = (byte) (val >>> 24);
}
static void putFloat(byte[] b, int off, float val) {
putInt(b, off, Float.floatToIntBits(val));
}
static void putLong(byte[] b, int off, long val) {
b[off + 7] = (byte) (val );
b[off + 6] = (byte) (val >>> 8);
b[off + 5] = (byte) (val >>> 16);
b[off + 4] = (byte) (val >>> 24);
b[off + 3] = (byte) (val >>> 32);
b[off + 2] = (byte) (val >>> 40);
b[off + 1] = (byte) (val >>> 48);
b[off ] = (byte) (val >>> 56);
}
static void putDouble(byte[] b, int off, double val) {
putLong(b, off, Double.doubleToLongBits(val));
}
}
至于为什么上述操作要&0xFF的原因如下:
保持二进制补码的一致性 因为byte类型字符是8bit的 而int为32bit 会自动补齐高位1 所以与上0xFF之后可以保持高位一致性 当byte要转化为int的时候,高的24位必然会补1,这样,其二进制补码其实已经不一致了,&0xff可以将高的24位置为0,低8位保持原样,这样做的目的就是为了保证二进制数据的一致性。
原文:https://blog.csdn.net/xiaozhouchou/article/details/79086604
补码的原因,over
标签:starting into pack com oid .net offset gbk int
原文地址:https://www.cnblogs.com/KanHin/p/10063144.html