c - 如何在 C 语言中将 4 个字母的 ascii 单词复制到缓冲区?

标签 c buffer ascii memcpy

我正在尝试将单词: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");
}  

这是我在控制台中得到的结果:
enter image description here

如果我使用 memcpy,为什么我会从位打印中获得不同的值?

不知道它是否与大小端有关,但我在这里丢失了 4 位 1,因此在这两种方法中都不会发生这种情况。

最佳答案

当你打电话时

print_bits(buffer[0]);

您只从缓冲区中取出一个字节,将其转换为unsigned int,然后将其传递给函数。 buffer 中的其他字节将被忽略。

关于c - 如何在 C 语言中将 4 个字母的 ascii 单词复制到缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44577278/

相关文章:

c++ - 使用arm-musl交叉编译,ERROR> proc_open : hidden symbol `__init_array_end' in proc_open is referenced > by DSO

Node.js zlib gzip 缓冲区在存档内为 "file"

java - 如何设置Java nio套接字的发送和接收缓冲区大小

java - 使用 FileInputStream 和 FileOutputStream 作为缓冲区

c - 为什么MTK只显示 'F'

R - 如何下载 ascii 光栅并解压缩?

c - 根据宏中的条件选择结构成员

java - float 比较

excel - 将 Hex 文件转换为 Excel 文件

c - 获取本地时间(以毫秒为单位)