2.60 Replace Byte

★★

Problem:

Suppose we number the bytes in a w-bit word from 0 (least significant) to w/8-1 (most significant). Write code for the following C function, which will return an unsigned value in which byte i of argument x had been replaced by byte b:

unsigned replace_byte(unsigned x, int i, unsigned char b);

code:

#include <stdio.h>
#include <assert.h>

unsigned replace_byte(unsigned x, int i, unsigned char b) {
    if(i < 0) {
        printf("error: i is negative\n");
        return x;
    }
    if(i > sizeof(unsigned)) {
        printf("error: i is too big\n");
        return x;
    }

    // byte i should left shift i << 3 bits
    unsigned mask = ((unsigned)0xff) << (i << 3);
    unsigned des_byte = ((unsigned)b) << (i << 3);
    return (x & ~mask) | des_byte;
}

int main() {
    unsigned x = 0x12345678;
    assert(replace_byte(x, 2, 0xab)==0x12ab5678);
    assert(replace_byte(x, 0, 0xab)==0x123456ab);
}

Last updated