问题描述
嘿,我想知道如何将C中的Int数组转换为字节数组,以及声明方法是什么.如果它更简单并且不使用指针,我将不胜感激.谢谢你的评论
hey i would like to know how you could cast an Int array in C to an byte array and what would be the declaration method. I would appreciate if it is simpler and no use of pointers. thanks for the comments
ex:将int addr [500]转换为byte []
ex: int addr[500] to byte[]
另外,我还希望结尾字节数组具有相同的数组名称.
Plus I would also want the ending byte array to have the same array name.
推荐答案
如果,您试图将int数组后面的内存作为字节数组进行重新解释,并且只有这样:
If you are trying to reinterpret the memory behind the int array as an array of bytes, and only then:
int ints[500];
char *bytes = (char *) ints;
您不能执行此操作而不求助于指针强制转换,因为声明[]
数组意味着在堆栈上进行分配,并且不能用于重新解释现有内存.
You cannot do this without resorting to pointer casting, as declaring a []
array implies allocation on stack, and cannot be used for reinterpretation of existing memory.
很显然,您需要知道自己在做什么.对于每个int
,通常会有4个char
(通常取决于平台等),因此您的新数组将具有500*4
个元素.查看以下内容的输出:
Obviously, you need to know what you are doing. For each int
there will be (typically, depending on platform etc.) 4 char
s, so your new array would have 500*4
elements. Check out what the output of:
printf("char size: %d, int size: %d", sizeof(char), sizeof(int));
告诉您要确定.
如果,您尝试将每个int
解释为char
,即要获得与int
相同的char
个数,则您不能不进行循环和手动转换(通常到新的内存位置)就无法做到这一点.
If you are trying to interpret each int
as a char
, i.e. to get the same number of char
s, as there were int
s, then you cannot do this without a loop and manual conversion (to a new memory locaton, normally).
这篇关于如何在C中将int数组转换为字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!