将 int
放入 char
数组的最佳方法(性能)是什么?
这是我当前的代码:
data[0] = length & 0xff;
data[1] = (length >> 8) & 0xff;
data[2] = (length >> 16) & 0xff;
data[3] = (length >> 24) & 0xff;
data
是一个 char
数组(共享 ptr),length
是 int
。
最佳答案
你在找memcpy吗
char x[20];
int a;
memcpy(&a,x,sizeof(int));
您的解决方案也很好 endian safe 。
旁注:-
虽然没有这样的保证 sizeof(int)==4
对于任何特定的实现。
关于c++ - 将 int 转换为 char 数组的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19497701/