新手问题。
比方说,我有十六进制数0xABCDEF,我怎么把它分成0xAB,0xCD和0xEF? 是这样的吗?
unsigned int number = 0xABCDEF
unsigned int ef = a & 0x000011;
unsigned int cd = (a>>8) & 0x000011;
unsigned int ab = (a>>16) & 0x000011;
由于
答案 0 :(得分:13)
使用0xff
作为掩码删除除数字8位以外的所有内容:
unsigned int number = 0xABCDEF
unsigned int ef = number & 0xff;
unsigned int cd = (number>>8) & 0xff;
unsigned int ab = (number>>16) & 0xff;
答案 1 :(得分:3)
unsigned int number = 0xABCDEF
unsigned int ef = number & 0xff;
unsigned int cd = (number >> 8) & 0xff;
unsigned int ab = (number >> 16) & 0xff;
而不是按位和(&
)操作,您可能希望ef
,cd
,ab
为unsigned char
类型,具体取决于其余代码以及您如何使用这些变量。在这种情况下,您转为unsigned char
:
unsigned int number = 0xABCDEF
unsigned char ef = (unsigned char) number;
unsigned char cd = (unsigned char) (number >> 8);
unsigned char ab = (unsigned char) (number >> 16);
答案 2 :(得分:0)
要使用的掩码为0xFF
,而不是0x11
。除此之外,你是对的。
答案 3 :(得分:0)
void splitByte(unsigned char * split, unsigned int a,int quantBytes)
{
unsigned char aux;
int i;
for(i=0;i<quantBytes;i++)
{
split[i]=a&0x00FF;
a=(a>>8);
}
for(i=0;i<quantBytes-1;i++)
{
aux = split[i];
split[i] = split[quantBytes-i-1];
split[quantBytes-i-1] = aux;
}
}
主要: unsigned char split [4]; splitByte(split,0xffffffff,4);