> For the complete documentation index, see [llms.txt](https://valineliu.gitbook.io/deuterium-wiki/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://valineliu.gitbook.io/deuterium-wiki/reading/cs-jing-dian-shu-ji/csapp-3e-homework-solution/2.-representing-and-manipulating-information/2.60-replace-byte.md).

# 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`:

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

code：

```c
#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);
}
```

###
