TheWaterProgrammer
TheWaterProgrammer

Reputation: 8239

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 chars & a vector of 16 bit unsigned shorts

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. Thats cool. I want to know if it is possible to typecast & store the sixteen_bit_array & into the eight_bit_array & How ?

I have a method which returns the eight_bit_array by returning a pointer to unsigned char like so:

// 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 *

Please suggest how to do this.

Upvotes: 0

Views: 2517

Answers (2)

Hatted Rooster
Hatted Rooster

Reputation: 36483

You could do some memcpy magic but you need to make sure your types are actually 8 and 16 bits respectively:

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

Upvotes: 2

nefas
nefas

Reputation: 1130

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)

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:

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

Upvotes: 1

Related Questions