C++ 将 int 转换为 char 数组的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19497701/
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
Optimal way to convert an int into a char array
提问by Kacper Fa?at
What is the best method (performance) to put an int
into a char
array?
This is my current code:
将 anint
放入char
数组的最佳方法(性能)是什么?这是我当前的代码:
data[0] = length & 0xff;
data[1] = (length >> 8) & 0xff;
data[2] = (length >> 16) & 0xff;
data[3] = (length >> 24) & 0xff;
data
is a char
array (shared ptr) and length
is the int
.
data
是一个char
数组(共享 ptr)并且length
是int
.
回答by Rahul Tripathi
Are you looking for memcpy
你在找 memcpy
char x[20];
int a;
memcpy(&a,x,sizeof(int));
Your solution is also good as it is endian safe.
您的解决方案也很好,因为它是endian safe。
On a side note:-
附注:-
Although there is no such guarantee that sizeof(int)==4
for any particular implementation.
尽管sizeof(int)==4
对于任何特定的实现都没有这样的保证。
回答by Yochai Timmer
Just use reinterpret_cast
. Use the data array as if it were an int pointer.
只需使用reinterpret_cast
. 像使用 int 指针一样使用数据数组。
char data[sizeof(int)];
*reinterpret_cast<int*>(data) = length;
BTW memcpy
is much slower than this, because it copies byte by byte using a loop.
In the case of an integer, this will just be a straightforward assignment.
顺便说一句,memcpy
比这慢得多,因为它使用循环逐字节复制。
在整数的情况下,这只是一个简单的赋值。