C++ 将短整数复制到字符数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2952895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
copying a short int to a char array
提问by cateof
I have a short integer variable called s_int that holds value = 2
我有一个名为 s_int 的短整数变量,它保存 value = 2
unsighed short s_int = 2;
I want to copy this number to a char array to the first and second position of a char array.
我想将此数字复制到字符数组到字符数组的第一个和第二个位置。
Let's say we have char buffer[10];
. We want the two bytes of s_int
to be copied at buffer[0]
and buffer[1]
.
假设我们有char buffer[10];
. 我们希望s_int
在buffer[0]
和 处复制的两个字节buffer[1]
。
How can I do it?
我该怎么做?
回答by crazyscot
The usual way to do this would be with the bitwise operators to slice and dice it, a byte at a time:
通常的方法是使用按位运算符对它进行切片和切块,一次一个字节:
b[0] = si & 0xff;
b[1] = (si >> 8) & 0xff;
though this should really be done into an unsigned char
, not a plain char
as they are signed on most systems.
尽管这真的应该在 . 中完成unsigned char
,而不是char
在大多数系统上签名的普通文件中。
Storing larger integers can be done in a similar way, or with a loop.
可以用类似的方式或循环来存储更大的整数。
回答by James
*((short*)buffer) = s_int;
*((short*)buffer) = s_int;
But viator emptorthat the resulting byte order will vary with endianness.
但是Viator emptor表示生成的字节顺序将随字节顺序而变化。
回答by Thomas Matthews
By using pointers and casts.
通过使用指针和强制转换。
unsigned short s_int = 2;
unsigned char buffer[sizeof(unsigned short)];
// 1.
unsigned char * p_int = (unsigned char *)&s_int;
buffer[0] = p_int[0];
buffer[1] = p_int[1];
// 2.
memcpy(buffer, (unsigned char *)&s_int, sizeof(unsigned short));
// 3.
std::copy((unsigned char *)&s_int,
((unsigned char *)&s_int) + sizeof(unsigned short),
buffer);
// 4.
unsigned short * p_buffer = (unsigned short *)(buffer); // May have alignment issues
*p_buffer = s_int;
// 5.
union Not_To_Use
{
unsigned short s_int;
unsigned char buffer[2];
};
union Not_To_Use converter;
converter.s_int = s_int;
buffer[0] = converter.buffer[0];
buffer[1] = converter.buffer[1];
回答by ShinTakezou
I would memcpy it, something like
我会 memcpy 它,像
memcpy(buffer, &s_int, 2);
The endianness is preserved correctly so that if you cast buffer into unsigned short *, you can read the same value of s_int the right way. Other solution must be endian-aware or you could swap lsb and msb. And of course sizeof(short) must be 2.
字节顺序被正确保留,因此如果您将缓冲区转换为 unsigned short *,您可以以正确的方式读取 s_int 的相同值。其他解决方案必须是字节序的,否则您可以交换 lsb 和 msb。当然 sizeof(short) 必须是 2。
回答by M. Williams
If you don't want to make all that bitwise stuff you could do the following
如果您不想制作所有按位的东西,您可以执行以下操作
char* where = (char*)malloc(10);
short int a = 25232;
where[0] = *((char*)(&a) + 0);
where[1] = *((char*)(&a) + 1);