用short填充整数数组的有效方法

时间:2015-07-10 16:18:27

标签: c

我正在尝试用另一个数组中的短整数填充无符号整数数组(32位)(大小不固定)。我在输出数组中一个接一个地放入短整数,其中包含随机值。

这是我的代码:

#define K_LENGTH (37) // Arbitrary

void computeInput(unsigned short* input) {
    unsigned int output[1000];
    unsigned int i, j, gap;

    j = 0;
    gap = 0;
    output[0] = 0;

    for (i = 0; i < K_LENGTH; i++) {
        output[j] |= (input[i] << gap);

        if (gap) {
            gap = 0;
            j += 1;
            output[j] = 0;
        } else {
            gap = 16;
        }
    }

    // The rest of output array is set to 0
    for (i = j, i < 1000, i++) {
        output[i] = 0;
    }

    // Other stuff
}

首先,检查间隙值的算法部分非常难看,但我不知道如何有效地执行此操作。其次,我不知道如何确保随机值被输入值擦除/替换。

在计算输入值之前,我应该将整个输出数组设置为0吗?这似乎效率低下。

2 个答案:

答案 0 :(得分:1)

我假设您正在尝试将16位无符号整数成对地合并为32位无符号整数数组:

#include <stdint.h>

void mergeShorts(size_t out_len, uint32_t output[out_len],
            size_t in_len, const uint16_t input[in_len] ) {

    size_t i;

    // output must have enough entries.
    assert( (in_len < SIZE_MAX) && ((in_len + 1) / 2 <= out_len) );

    for ( i = 0 ; i < in_len / 2 ; i += 1 )
        output[i] = ((uint32_t)input[i / 2] << 16) | (input[i / 2 + 1];

    // transfer last (odd) entry
    if ( (i * 2) < in_len )
        output[i++] = (uint32_t)input[in_len - 1] << 16;

    // zero the rest of the array
    for ( ; i < out_len ; i++ )
        output[i] = 0;
}

使用stdint.h类型可以保证两个数组元素的大小合适,并且可能是您真正想要的。

如果您只有固定尺寸,请用常数替换out_lenin_len。我使用output作为参数,因为缺少其余的代码。如果这不是必需的,只需再次将其设为本地(名称output实际上意味着调用者期望它。)

通常情况下,我会将其打包成一个函数,并使用适当的参数从computeInput调用该函数:

mergeShorts(1000, output, K_LENGTH, input);

答案 1 :(得分:0)

这似乎是Mr. memcpy的作品 我会尝试使用memcpy来解决您的问题 它非常确定副本是高效的,因为它将一个对象的位复制到另一个对象中,完全没有任何算术,只是按位。

无论如何,我可以看到你正在承担很多非便携式问题 例如,unsigned int是32位,没有任何填充位 该标准仅确保unsigned int保持16位的最小值 也许最好使用uint_least32_t中定义的无符号整数类型uint_fast32_tstdint.h,总是至少有32位。如果幸运的话,那里也会定义uint32_t类型,它只有32位。

相关问题