uint16转化为uint8类型为什么会造成数据截断
在计算机科学中,uint16类型通常表示一个16位的无符号整数,而uint8类型则表示一个8位无符号整数。当把一个uint16类型的变量转换为uint8类型的变量时,会发生数据截断。
因为uint8类型只能容纳8位的二进制数据,而uint16类型却有16位的二进制数据,因此在将uint16转换为uint8类型时,原数据的高8位数据会被截断丢弃,只保留低8位数据。这就是数据截断的原因。
例如,如果一个uint16类型的变量值为1000000000000011,以二进制表示为0b00000000 10000000 00000011,如果将其转换为uint8类型,只保留低8位,即0b00000011就会丢失高8位0b00000000 10000000。这就造成了数据截断。
因此,在进行变量类型转换时,程序员需要注意数据范围及目标数据类型能够容纳的数据范围,避免数据截断造成程序出错。
因此组合数据的时候RPMSend会&0XFF00>>8,将原先高八位的数据右移到低8位,强转位uinit8_t,保留了低8位的数据。
组合接收的数据:
uint16_t DCCompressor.LineCurren;
DCCompressor.LineCurrent = (uint16_t)((CompRecvBuff[27]<<8)+CompRecvBuff[28])
驱动函数:
void SendToCompDriver(uint16_t RPMSend, uint8_t type)
{
static uint8_t task=0;
uint16_t crcData;
uint8_t Send;
// if(DCCompressor.CommIndex>=60)
// Systemalarm.DCCompCommAlarm=1;
// else
// Systemalarm.DCCompCommAlarm=0;
if(DCCompressor.CommIndex<60)
{
DCCompressor.CommIndex++;
Systemalarm.DCCompCommAlarm=0;
}
else
Systemalarm.DCCompCommAlarm=1;
switch(task)
{
case 0://set compressor speed
task++;
break;
case 1:
if(RPMSend>0)
{
Send = 0x01;
}
else
{
Send = 0x00;
}
CompSendBuff[0] =0x01;
CompSendBuff[1] =0x10;
CompSendBuff[2] =0x19;
CompSendBuff[3] =0x02;
CompSendBuff[4] =0x00;
CompSendBuff[5] =0x02;
CompSendBuff[6] =0x04;
CompSendBuff[7] =0x00;
CompSendBuff[8] =Send;
CompSendBuff[9] =(uint8_t)(((RPMSend/6)&0xFF00)>>8);
CompSendBuff[10] =(uint8_t)((RPMSend/6)&0x00FF);
crcData = crc16(CompSendBuff, 11);
CompSendBuff[11] =(uint8_t)((crcData>>8)&0x00FF);
CompSendBuff[12] =(uint8_t)(crcData&0x00FF);
CompSendCount=13;
beginCompSend();
task++;
break;
case 2:
task++;
break;
case 3://Read drive data
CompSendBuff[0] =0x01;
CompSendBuff[1] =0x03;
CompSendBuff[2] =0x15;
CompSendBuff[3] =0x1E;
CompSendBuff[4] =0x00;
CompSendBuff[5] =0x17;
crcData = crc16(CompSendBuff, 6);
CompSendBuff[6] =(uint8_t)((crcData>>8)&0x00FF);
CompSendBuff[7] =(uint8_t)(crcData&0x00FF);
CompSendCount=8;
beginCompSend();
task=0;
break;
default:
task=0;
break;
}
}