将两个8位阵列组合到USHORT(16位),无需循环

use*_*181 1 c c++

我需要将两个UCHAR(8位)数组合并到C中的USHORT(16位)值.但我必须在不使用"for"或任何循环的情况下执行此操作.

如:

UCHAR A[1000], B[1000];
USHORT C[1000];
Run Code Online (Sandbox Code Playgroud)

结果必须如下:

C[0] = {A[0], B[0]};
C[1] = {A[1], B[1]};
...
C[1000]={A[1000], B[1000]};
Run Code Online (Sandbox Code Playgroud)

nea*_*gab 5

uint8_t one = 0xBA;
uint8_t two = 0xBE;

uint16_t both = one << 8 | two;
Run Code Online (Sandbox Code Playgroud)

更新: 也许我没有理解你的问题......但如果你想将uint8_t数组转换为uint16_t数组 - >检查大小和强制转换

uint8_t array[100];
uint16_t array_ptr_ushort* =(uint16_t*)&array[0];
Run Code Online (Sandbox Code Playgroud)

确保阵列的大小均匀.

UPDATE2:

uint8_t array1[100];
uint8_t array2[100];
uint16_t combined[100];

memcpy(combined, array1, sizeof(array1))
memcpy((uint8_t*)combined + sizeof(array1), array2, sizeof(array2))
Run Code Online (Sandbox Code Playgroud)

UPDATE3:

如果没有某种循环,你不能在一个连续数组中组合两个数组,即使你使用DMA,循环也会存在于底层硬件中......

UPDATE4:

你可以递归地做.

#include "stdafx.h"
#include <cstdint>
#include <algorithm>

uint8_t arrayA[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
uint8_t arrayB[] = {0xA, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1};
uint16_t array_combined[sizeof(arrayA)] = {};
static_assert(sizeof(arrayA) == sizeof(arrayB), "Arrays of different sizes");

uint16_t combine(const uint8_t *a, const uint8_t *b, uint16_t *put, uint32_t size)
{
    uint16_t value = (*a << 8) | *b;
    if(size)
        *put = combine(++a, ++b, ++put, --size);
    return value;
}

void combine_arrays(const uint8_t *a, const uint8_t *b, uint16_t *put, uint32_t size)
{
    *put = combine(a, b, put, size);
}

int _tmain(int argc, _TCHAR* argv[])
{

    combine_arrays(arrayA, arrayB, array_combined, sizeof(arrayA));

return 0;
}
Run Code Online (Sandbox Code Playgroud)

UPDATE5: C++中带有static_assert的C版本

#include <stdint.h>


uint8_t array1[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
uint8_t array2[] = {0xA, 0x9, 0x8, 0x7, 0x6, 0x5, 0x4, 0x3, 0x2, 0x1};
uint16_t array_combined[sizeof(array1)] = {};
static_assert(sizeof(array1) == sizeof(array2), "Arrays of different sizes");

int _tmain(int argc, _TCHAR* argv[])
{

    int size = sizeof(array1);
    int count = 0;
    do
    {
        array_combined[count] = (array2[count] << 8) | array1[count];
    }while(count++ != size);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

更新6:还有C++方法来实现这个目标......