【发布时间】:2017-06-15 21:25:01
【问题描述】:
我正在尝试将单词:0x0FF0 复制到缓冲区,但无法这样做。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <math.h>
#include <time.h>
#include <linux/types.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
void print_bits(unsigned int x);
int main(int argc, char *argv[])
{
char buffer[512];
unsigned int init = 0x0FF0;
unsigned int * som = &init;
printf("print bits of som now: \n");
print_bits(init);
printf("\n");
memset(&buffer[0], 0, sizeof(buffer)); // reinitialize the buffer
memcpy(buffer, som, 4); // copy word to the buffer
printf("print bits of buffer[0] now: \n");
print_bits(buffer[0]);
printf("\n");
return 0;
}
void print_bits(unsigned int x)
{
int i;
for (i = 8 * sizeof(x)-17; i >= 0; i--) {
(x & (1 << i)) ? putchar('1') : putchar('0');
}
printf("\n");
}
如果我使用 memcpy,为什么我会从位打印中得到不同的值?
不知道它是否与 big-little-endian 有关,但我在这里丢失了 4 位 1,所以在这两种方法中都不应该发生。
【问题讨论】:
-
不要发布文字图片!
-
不要使用幻数!
sizeof(unsigned int)不保证是4,分别。 32 位。而且代码太复杂了。在您的平台上,char的签名是哪个?多少位?