我正在尝试将单词: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,为什么我会从位打印中获得不同的值?
不知道它是否与大小端有关,但我在这里丢失了 4 位 1,因此在这两种方法中都不会发生这种情况。
最佳答案
当你打电话时
print_bits(buffer[0]);
您只从缓冲区中取出一个字节,将其转换为unsigned int
,然后将其传递给函数。 buffer
中的其他字节将被忽略。
关于c - 如何在 C 语言中将 4 个字母的 ascii 单词复制到缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44577278/