简体   繁体   English

如何将16位unsigned int转换为8位unsigned char并最终返回unsigned char *?

[英]How to convert 16 bit unsigned int to 8 bit unsigned char & finally return in an unsigned char*?

I have a vector of 8 bit unsigned char s & a vector of 16 bit unsigned short s 我有一个8位 unsigned char的向量和一个16位 unsigned short的向量

std::vector<unsigned char> eight_bit_array;
std::vector<unsigned short> sixteen_bit_array;

sixteen_bit_array.resize(x_number_of_samples);
eight_bit_array.resize((x_number_of_samples)*2);

I have populated some data into the sixteen_bit_array . 我已经将一些数据填充到sixteen_bit_array Thats cool. 这很酷。 I want to know if it is possible to typecast & store the sixteen_bit_array & into the eight_bit_array & How ? 我想知道是否有可能进行类型转换并将sixteen_bit_array和存储到eight_bit_array以及如何进行?

I have a method which returns the eight_bit_array by returning a pointer to unsigned char like so: 我有一个方法,它通过返回一个指向unsigned char的指针来返回eight_bit_array ,如下所示:

// A legacy method which returns the char array
unsigned char *GetDataSample(std::size_t sample_number) {
    return &eight_bit_array[sample_number];
}

So I want to typecast & store the sixteen_bit_array into the eight_bit_array so that I can return 16 bit unsigned ints without having to change the return type of my legacy method from unsigned char * to unsigned short * 因此,我想将sixteen_bit_array类型转换并存储到eight_bit_array以便可以返回16 bit unsigned ints而不必将传统方法的返回类型从unsigned char *更改为unsigned short *

Please suggest how to do this. 请提出如何做到这一点。

You could do some memcpy magic but you need to make sure your types are actually 8 and 16 bits respectively: 您可以做一些memcpy魔术,但需要确保类型实际上分别是8位和16位:

#include <cstdint>
#include <vector>
#include <cstring>

int main() {
    std::vector<uint16_t> uint16vals{11, 1, 0, 3};
    std::vector<uint8_t> uint8vals(uint16vals.size() * 2);
    std::memcpy(&uint8vals[0], &uint16vals[0], sizeof(uint16_t) * uint16vals.size());
}

You can use bitwise operations: 您可以使用按位运算:

std::pair<unsigned char, unsigned char> split(unsigned short n) {
    // set to 0 the bit outside of a 8bit unsigned int
    unsigned char low = n & (1 << 8);
    // get the bit higher than 2^8
    unsigned char high = n >> 8;
    return {high, low};
}

(The shift value should be good but TBH I'm not 100% sure) (移位值应该不错,但是我不确定TBH 100%确定)

BTW, use fixed size type and not implementation dependant size type when you make assumption on the size of the type 顺便说一句,当您对类型的大小进行假设时,请使用固定大小类型而不是与实现相关的大小类型

EDIT 编辑

to merge two 8 bit integer you can do something like this: 合并两个8位整数,您可以执行以下操作:

unsigned short split(unsigned char h, unsigned char l) {
    return (h << 8) + l;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM