字节序,原码和补码与位运算

  计算机最小的数据获取单元就是字节,一个字节byte = 8个位 bit,八个位是用二进制的形式保存的。假如11111111,如果是无符号数那么可以保存0-255一共256(2的八次方)个数的数,如果是有符号那么第一个位是符号位也就是 如果是1就是负数,如果是0就是正数。一共可以保持-128到127范围的数字。

  原码和补码,之所以出现这样的概念就是为了计算机更好的计算。正数的原码就是其补码,而负数的补码,首先把其正数的原码符号位变成1 其余位按位取反 最后加 1。

  字节序,分成大端序和小端序。对于一个字节的数据没有顺序的说法但是对于多个字节去表示一个数字比如int类型那就牵扯到在内存地址中的顺序了。一般在计算机内存中都是小端序,也就是低字节(个十百中的个位叫地位)在内存的低地址,高字节在内存中的高地址。而大端序则相反,大端序通常用在网络传输上。所以变成本地内存中的字节序通常需要一个转序的操作。

  最后就是位运算,这里补上两个函数,java中short 和 byte数组的转换

  

 1 package com.xunluyaoyao.tools;
 2 
 3 public class ByteSortTools {
 4     public static short[] byteToShort(byte[] source) {
 5         if (source == null || source.length == 0) {
 6             return null;
 7         }
 8         int times = source.length / 2;
 9         if (source.length % 2 != 0) {
10             times += 1;
11         }
12         short[] result = new short[times];
13         for (int i = 0; i < source.length / 2; i++) {
14             short tmp = (short)(source[2 * i + 1] << 8 + source[2 * i]);
15             result[i] = tmp;
16         }
17         if (times != source.length / 2) {
18             result[times] = (short)source[source.length - 1];
19         }
20         return result;
21     }
22     public static void printArray(short[] source) {
23         if (source == null) {
24             return;
25         }
26         for (int i = 0; i < source.length; i++) {
27             System.out.println(source[i]);
28         }
29     }
30 
31     public static void main(String[] args) {
32         byte[] bArray = new byte[]{0, 1, 0, 1};
33         printArray(byteToShort(bArray));
34     }
35 }

输出结果 256 256

猜你喜欢

转载自www.cnblogs.com/xunluyaoyao/p/9692117.html