1、原码和补码
//超出byte表示范围的数编译器自动识别报错
//计算机和手机中的数默认用补码表示
//负数求补码 原码符号位不变,数值位取反加一
//负数求原码 补码符号位不变,数值位取反加一
byte a = 127;//Byte.MAX_VALUE
byte c = -128;//Byte.MIN_VALUE 1000,0000 0x80 0200
2、无符号byte的用途及处理
unsigned byte可表示0-255的数,signed byte表示-128-127的数。无符号byte可表示更大的自然数。
//一般设备数据都是非负整数,用无符号byte表示。但计算机接收后把它当signed byte处理
//无符号byte1000,0001(129)当补码处理就是-127
//int11111111,11111111,11111111,10000001
byte b = -127;//无符号byte须用int表示
//11111111,11111111,11111111,10000001 &
//00000000,00000000,00000000,11111111
int i = b&0xff;//先将byte转化为int,然后取最低位字节
3、求校验和
一般从远程接收过来的数据有可能出错,会有个校验位。求出的校验和跟校验位比较,若相等说明正确;若不等说明数据有误,抛弃重新接收。
1)发送端所有数据字节求异或,得出的字节为校验字节,将数据字节和校验字节拼接发送。在接收端,所有字节求异或,得出的字节为0则说明正确。
byte[] bytes = new byte[]{77,55,48,56,49,45,73,84,51,48,49};//65
byte checkSum = 0;
for(int i=0;i<bytes.length;i++){
checkSum ^= bytes[i];//两个byte取异或
}
System.out.println("求校验位的值:"+checkSum);
2)CRC16校验Java实现
/**
* CRC-16校验,校验位为俩字节
*/
public class CRC16 {
public static int get_crc16 (byte[] bufData, int buflen, byte[] pcrc){
int ret = 0;
int CRC = 0x0000ffff;
int POLYNOMIAL = 0x0000a001;
int i, j;
if (buflen == 0){
return ret;
}
for (i = 0; i < buflen; i++){
CRC ^= ((int)bufData[i] & 0x000000ff);
for (j = 0; j < 8; j++){
if ((CRC & 0x00000001) != 0){
CRC >>= 1;
CRC ^= POLYNOMIAL;
}else{
CRC >>= 1;
}
}
}
System.out.println(Integer.toHexString(CRC));
pcrc[0] = (byte)(CRC & 0x00ff);
pcrc[1] = (byte)(CRC >> 8);
return ret;
}
public static void main(String[] args){
byte[] aa = {0x5A,0x05,0x1A};//4F53
byte[] bb = new byte[2];//用于接收校验字节
get_crc16(aa, aa.length, bb);
System.out.println(Integer.toHexString((int)bb[0] & 0x000000ff));
System.out.println(Integer.toHexString((int)bb[1] & 0x000000ff));
}
}
4、移位和取反
//按补码处理,包括符号位移动
//左移,右边补0;右移,负数左边补1,正数左边补0
System.out.println(Integer.toBinaryString(Integer.MIN_VALUE<<2));
System.out.println(Integer.toBinaryString(Integer.MIN_VALUE>>1));
System.out.println(Integer.toBinaryString(Integer.MIN_VALUE));
System.out.println(Integer.toBinaryString(~1));//补码全部位取反,-2
5、表示特别大的整数、小数
//大概21亿
int i = Integer.MAX_VALUE;//2^31-1
long l2 = Long.MAX_VALUE;//2^63-1
//继承Number,用字符串表示
BigInteger bi = new BigInteger("9999999999999999999999999999999");
bi.add(BigInteger.TEN);//提供专门运算方法
BigDecimal bd = new BigDecimal("44444444444444444444.44444444");
//浮点数表示的最大值远大于整数
float f2 = Float.MAX_VALUE;//(2-2^-23)·2^127
float f3 = Float.MIN_VALUE;//2^-149
double d = Double.MAX_VALUE;//(2-2^-52)*2^1023
double d2 = Double.MIN_VALUE;//2^-1074