Treating 8-bit int array as 16-bit int array?

Jun 24, 2011 at 9:50pm
I am trying to see if there is a way to quickly convert an 8-bit array of numbers into a 16-bit array of numbers. Basically, I get data from an outside piece of hardware that I need to display on the screen. Right now the data is treated as 8-bit integers, even though I technically need 16-bit integers. What my code does is take two adjacent values and multiplies them, here is an example:

Byte1 = 3
Byte2 = 11

Value = Byte2*256 + Byte1 = 2819

This works, but I have a *lot* of these data points (it's basically a 1024x768 image) so there are many of these calculations. I am wondering if there is a way to speed this up. So right now:

Byte1 = 00000011
Byte2 = 00001011

And I want to have the program just take 0000101100000011 as its value. I do *not* want to just caste the values into a short, because that will just give me 0000000000000011 and 0000000000001011 and not accomplish anything, as far as I understand.

Basically I'm trying to get a pointer to an array of 8-bit integers and tell my program "OK, now they are 16-bit integers and there are only half as many of them."

How do I do that, if it's possible at all?
Jun 24, 2011 at 9:54pm
So you want to convert char* to short*?
1
2
3
4
char* chars = new char[20];
//fill chars with data
short* shorts = reinterpret_cast<short*>(chars);
//now handle shorts as an array with a size of 10 
Note: changing data in shorts will change data in chars too, and vice-versa.

Another option is a nameless union:
1
2
3
4
5
union
{
  char chars[20];
  short shorts[10];
};
Last edited on Jun 24, 2011 at 9:56pm
Jun 24, 2011 at 10:08pm
You could try streaming the data to a buffer as the two chars and reading it back as a short int.
Jun 24, 2011 at 10:20pm
WarPhalange wrote:
And I want to have the program just take 0000101100000011 as its value. I do *not* want to just caste the values into a short, because that will just give me 0000000000000011 and 0000000000001011 and not accomplish anything, as far as I understand.



Dont cast the values - cast the array name (whic is a pointer) to a pointer to short.
1
2
3
4
5
6
7
    // poor example  
    char some_vals[] =  {3,11}; //some char/byte array
    
    short *pshort = (short*) some_vals;

    //test
    cout << pshort[0]; //outputs 2819 decimal 

Jun 25, 2011 at 12:06am
I tried your method, guestgulkan, and am happy to report that it works!

Just to make sure before I dive into it, this should be faster than my previous method, right?
Jun 25, 2011 at 12:21am
Yeah, because instead of performing multiplication and addition, you're just handling the data in a different way.
Jun 25, 2011 at 9:37am
@WarPhalange

Note that this will only work on LSB machines (like Intel).
If you ever compile this on a MSB machine you will have to swap each byte1 and byte2.
Topic archived. No new replies allowed.