私は C が初めてで、unsigned int の特定のバイトを置き換える関数を作成しようとしています。ポインターはまだ少しあいまいです.replace_byte()のこれらのポインターを使用して、概念的に私のエラーが何であるかを正確に説明してくれませんか? 前もって感謝します :)
#include <stdio.h>
typedef unsigned char *byte_pointer;
void show_bytes(byte_pointer start, int length) {
int i;
for (i=0; i < length; i++) {
printf(" %.2x", start[i]);
}
printf("\n");
}
unsigned replace_byte(unsigned x, int i, unsigned char b) {
int length = sizeof(unsigned);
printf("X: ");
show_bytes(x, length);
printf("Replace byte position from left: %u\n", i);
printf("Replace with: %u\n", b);
printf("Combined: ");
int locationFromRight = (length - i - 1);
x[locationFromRight] = b;
show_bytes( (byte_pointer)&x, length);
}
int main(void) {
unsigned a = 0x12345678;
int loc = 2;
unsigned char replaceWith = 0xAB;
replace_byte(a, loc, replaceWith);
return 0;
}