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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:54:32  来源:igfitidea点击:

Optimal way to convert an int into a char array

c++arraystype-conversion

提问by Kacper Fa?at

What is the best method (performance) to put an intinto a chararray? 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;

datais a chararray (shared ptr) and lengthis the int.

data是一个char数组(共享 ptr)并且lengthint.

回答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)==4for 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 memcpyis 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比这慢得多,因为它使用循环逐字节复制。
在整数的情况下,这只是一个简单的赋值。

回答by Ivan Ishchenko

This is the only way. Theoretically you could use memcpyor reinterpret_castbut you can't due to problems with endians.

这是唯一的方法。从理论上讲,您可以使用memcpyorreinterpret_cast但由于endians 的问题而不能使用