我是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;
}
为什么你使用指针而不是按位和? – user1937198
对于bitewise操作符,我仍然很模糊。你知道任何可以描述我想要做什么的资源吗?我不知道该怎么谷歌来得到我需要的东西:) –
维基百科如何:http://en.wikipedia.org/wiki/Bitwise_operations_in_C – user1937198