[英]Copying unsigned char array to uint32_t, and vice versa
I'm trying to iteratively copy an unsigned char array to a uint_32t variable (in 4 byte blocks), perform some operation on the uint_32t variable, and copy it back to the unsigned char array.我正在尝试将 unsigned char 数组迭代复制到 uint_32t 变量(在 4 字节块中),对 uint_32t 变量执行一些操作,然后将其复制回 unsigned char 数组。
Here's my code:这是我的代码:
unsigned char byteArray[len]
for (int i=0; i<len; i+=4) {
uint32_t tmpInt = 0;
memcpy(&tmpInt, byteArray+(i*4), sizeof(uint32_t));
// do some operation on tmpInt here
memcpy((void*)(byteArray+(i*4)), &tmpInt, sizeof(uint32_t));
}
It doesn't work though.虽然它不起作用。 What's wrong, and how can I achieve what I want to do?
出了什么问题,我怎样才能实现我想做的事情?
The problem is that you are adding 4 to i
with each iteration and multiplying by 4. You should be using byteArray + i
.问题是你在每次迭代时将 4 添加到
i
并乘以 4。你应该使用byteArray + i
。
Also, as @WeatherVane pointed out below, your loop would be more consistent with a sizeof():此外,正如@WeatherVane 在下面指出的那样,您的循环将与 sizeof() 更加一致:
for (int i = 0; i < len; i += sizeof(uint32_t))
. for (int i = 0; i < len; i += sizeof(uint32_t))
。
As others pointed out you are doing too much by incrementing i
as well as multiplying it by the size of your target.正如其他人指出的那样,您通过增加
i
并将其乘以目标大小来做太多事情。
On top of this在此之上
sizeof
operator evaluates to size_t
not int
. sizeof
运算符的计算结果为size_t
而不是int
。 Fixing all, the result might look like this:修复所有问题,结果可能如下所示:
unsigned char byte_array[len];
typedef uint32_t target_type;
const size_t s = sizeof (target_type);
for (size_t i = 0; i < (len/s)*s; i += s) {
target_type target;
memcpy(&target, byte_array + i, s);
// do some operation on target here
memcpy(byte_array + i, &target, s);
}
To avoid the typedef
just define the target outside of the for
-loop:为了避免
typedef
,只需在for
循环之外定义目标:
unsigned char byte_array[len];
{
uint32_t target;
const size_t s = sizeof target;
for (size_t i = 0; i < (len/s)*s; i += s) {
memcpy(&target, byte_array + i, s);
// do some operation on target here
memcpy(byte_array + i, &target, s);
}
}
An equivalent to相当于
byte_array + i
would be将会
&byte_array[i]
which might be more intuitively to read.这可能更直观地阅读。
To avoid the "strange" (len/s)*s
one could step away from using an index at all, but use a pointer instead:为了避免“奇怪的”
(len/s)*s
,可以完全不使用索引,而是使用指针:
for (unsigned char p = byte_array; p < byte_array + len; p += s) {
memcpy(&target, p, s);
// do some operation on target here
memcpy(p, &target, s);
}
In my opinion this is a more elegant solution.在我看来,这是一个更优雅的解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.