gpt4 book ai didi

c++ - 将两个 8 位数组组合成一个 USHORT (16 位),无循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:18 24 4
gpt4 key购买 nike

我需要在 C 中将两个 UCHAR(8 位)数组组合成一个 USHORT(16 位)值。但我必须在不使用“for”或任何循环。

作为:

UCHAR A[1000], B[1000];
USHORT C[1000];

结果必须是:

C[0] = {A[0], B[0]};
C[1] = {A[1], B[1]};
...
C[1000]={A[1000], B[1000]};

最佳答案

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

uint16_t both = one << 8 | two;

更新:也许我不明白你的问题......但是如果你想将 uint8_t 数组转换为 uint16_t 数组-> 检查大小并转换

uint8_t array[100];
uint16_t array_ptr_ushort* =(uint16_t*)&array[0];

确保数组的大小是偶数。

更新 2:

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))

更新 3:

你不能在没有某种循环的情况下将两个数组组合成一个连续的数组,循环将存在于底层硬件中,即使你为此使用 DMA...

更新4:

你可以递归地做。

#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;
}

UPDATE5: C 版本带有来自 C++ 的 static_assert

#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;
}

UPDATE6:还有 C++ 方法可以实现这一点......

关于c++ - 将两个 8 位数组组合成一个 USHORT (16 位),无循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14958360/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com