按索引将字节插入多字节类型

Inserting a byte into a mutli byte type by index

我发现这个 answer 是一个类似的问题,其中可以从更大的类型中提取一个字节。我想知道的是,如果使用索引值,这个过程的逆过程是什么?

要从 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 在评论中对他的问题提出了很好的观点。我认为此时此刻,因为这将是 class 模板的构造函数的行为;我想插入和替换,而不是插入和移位。

示例:

unsigned int value = 0x01234567;
unsigned char a = 0x9D;
insertByte( a, value, 2 );
// value = 0x019D4567

只需将您的 char 转换为 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

bitwise-and的反义词是bitwise-or,right-shift的反义词是left-shift。剩下的问题是清除字节中的任何旧值,这是用新掩码完成的。 (如果忽略新掩码,这是一个 left-shift 后跟 bitwise-or。将其与用 right-shift 后跟 bitwise-and 提取字节进行比较。)

用户 1178830 的答案的当前修订版是一种更程序化的方式来完成此任务。