简体   繁体   English

在 C 中使用 memcpy 复制无符号字符数组

[英]Copying a unsigned char array using memcpy in C

int n=50;
unsigned char bytes[4];
unsigned char *buffer=(unsigned char*)malloc(sizeof(int));
bytes[0]=(n>>24)&0xFF;
bytes[1]=(n>>16)&0xFF;
bytes[2]=(n>>8)&0xFF;
bytes[3]=n&0xFF;

memcpy(buffer,bytes,sizeof(bytes));

This does not copy the bytes array to buffer.这不会将字节数组复制到缓冲区。 Any idea why??知道为什么吗? What can be done to copy the array to buffer??可以做些什么来将数组复制到缓冲区?

When I try to print the sizeof(buffer) or the contents after memcpy it shows 0 and no contents.当我尝试在 memcpy 之后打印 sizeof(buffer) 或内容时,它显示 0 并且没有内容。 I need to copy it to buffer as I have other information to append to the buffer along with bytes.我需要将它复制到缓冲区,因为我有其他信息要与字节一起附加到缓冲区。

 int n=50; 

Assuming that you are on a 32-bit machine, 'n' will be a 4-byte value.假设您使用的是 32 位机器,'n' 将是一个 4 字节的值。 n = 0x00000032 = 00000000b 00000000b 00000000b 00110010b n = 0x00000032 = 00000000b 00000000b 00000000b 00110010b

 unsigned char bytes[4];

bytes will ve a 4-byte value : bytes 将有一个 4 字节的值:

 bytes[0]=(n>>24)&0xFF;

byte[0] = 00000000b字节[0] = 00000000b

 bytes[1]=(n>>16)&0xFF;

byte[1] = 00000000b字节[1] = 00000000b

 bytes[2]=(n>>8)&0xFF;

byte[2] = 00000000b字节[2] = 00000000b

 bytes[3]=n&0xFF;

byte[3] = 00110010b字节[3] = 00110010b

memcpy(buffer,bytes,sizeof(bytes));

Copy (sizeof(bytes)) 4 bytes from bytes to buffer.将 (sizeof(bytes)) 4 个字节从字节复制到缓冲区。

Whether or not this does what you expect is perhaps the question.这是否符合您的预期也许是个问题。 (More assumptions) (更多假设)


Assuming that buffer is:假设缓冲区是:

int buffer[1];

the above statement would copy as expected.上述语句将按预期复制。 However, if you test this assumption using code usch as:但是,如果您使用以下代码测试此假设:

printf("buffer = %d\n", buffer[0]);

The output will depend on what kind of machine you run it on;输出将取决于您运行它的机器类型; little endian, or bit endian.小端,或位端。

On one, it will out put "buffer = 50" On the other, it will output the decimal value which is equivelant to:一方面,它会输出“buffer = 50”另一方面,它将输出十进制值,相当于:

0x32000000 (00110010b 00000000 00000000b 00000000b 00000000b)

Assuming:假设:

int buffer;

Will most likely generate a compiler warning (or error);很可能会产生编译器警告(或错误); and is probably not what you want, unless you change your memcpy() as follows:并且可能不是你想要的,除非你改变你的 memcpy() 如下:

memcpy(&buffer,bytes,sizeof(bytes));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM