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

时间:2019-05-17 02:17:01

标签: c++ byte c++17 logical-operators

我发现这个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在评论中表达了他的观点。我认为目前是因为这将是类模板的构造函数的行为。我要插入和替换,而不是插入和移位。

示例:

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

2 个答案:

答案 0 :(得分:2)

只需将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; 
}

答案 1 :(得分:1)

要反转从其他答案中得到的结果:

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

按位与和的对立是按位或,而右移的对立是左移。剩下的麻烦是清除字节中的任何旧值,这是使用新掩码完成的。 (如果您忽略了新的掩码,这是一个左移,然后是按位“或”。将其与通过右移后是按位“与”来提取字节进行比较)。

user1178830的答案的当前版本是实现此目的的更具编程性的方法。