我发现了一个类似问题的答案,可以从较大类型提取字节。我想知道的是,该过程的使用是使用索引值的反面?
从32位类型的用户皮特·威尔逊(Pete Wilson(提取字节:
int a = (the_int >> 24) & 0xff; // high-order (leftmost) byte: bits 24-31 int b = (the_int >> 16) & 0xff; // next byte, counting from left: bits 16-23 int c = (the_int >> 8) & 0xff; // next byte, bits 8-15 int d = the_int & 0xff; // low-order byte: bits 0-7
我想用索引值相反:
// assume int = 32bit or 4 bytes and unsigned char = 8bit or 1 byte
void insertByte( unsigned char a, unsigned int& value, unsigned idx ) {
// How to take byte and insert it into the byte position
// of value at idx where idx is [0-3] from the right
}
这是一个值:
的示例unsigned char a = 0x9D;
unsigned int value = 0;
insertByte( a, value, 0 ); // value = 0x0000009D;
insertByte( a, value, 1 ); // value = 0x00009D00;
insertByte( a, value, 2 ); // value = 0x009D0000;
insertByte( a, value, 3 ); // value = 0x9D000000;
// insertByte( a, value, >3 ); // invalid index
编辑
用户jamit在评论中对他的问题提出了很好的观点。我认为这一刻是因为这将是构造函数对班级模板的行为。我想插入和替换,而不是插入和移位。
示例:
unsigned int value = 0x01234567;
unsigned char a = 0x9D;
insertByte( a, value, 2 );
// value = 0x019D4567
只需将您的字符投入int并以所需的字节数字移动并将其添加到您的值中。
void insertByte( unsigned char a, int& value, unsigned int idx ) {
if(idx > 3)
return;
// Clear the value at position idx
value &= ~(0xff << (idx*8));
int tmp = a;
tmp = (tmp << (idx * 8));
// Set the value at position idx
value |= tmp;
}
将您从另一个答案中转换出来:
unsigned a = (the_int & 0x00ffffff) | (the_byte << 24); // set high-order byte: bits 24-31
unsigned b = (the_int & 0xff00ffff) | (the_byte << 16); // next byte, bits 16-23
unsigned c = (the_int & 0xffff00ff) | (the_byte << 8); // next byte, bits 8-15
unsigned d = (the_int & 0xffffff00) | (the_byte); // low-order byte: bits 0-7
位于位的相反,是钻头或右移的相反,左移。剩余的并发症是清除字节中的任何旧值,该值是用新面具完成的。(如果您忽略了新的掩码,这是一个左移,然后是一个位或位。将其与右移提取字节,然后是一个钻头,然后是。(
。(用户1178830的答案当前的修订是实现此目的的更具程序性的方法。