Reputation: 300
Using C++ (GCC specifically, should have put this sooner), I'm storing raw texture data in an array of unsigned bytes, in a RGBA format, with 32 bits per pixel (8 bits per color value with Alpha, so on and so forth...). The thing is, I want to write a function that returns the raw data as a array of Colors, where a Color is a struct defined as the following:
struct Color
{
uint8 r;
uint8 g;
uint8 b;
uint8 a;
};
Plus functions and whatnot, but those are the only variables in the struct. My thinking is that since each color is 4 bytes long, what I can somehow cast the raw byte array to a Color array that is 1/4 of the original size (in "length" of array, not in absolute size). I think that reinterpret_cast is what I am looking for, but I cannot find anything after a google search that confirms 100% that you can convert it into an array of structs instead of just one struct.
So I guess I am just asking someone to either confirm that this is indeed possible with reinterpret_cast
, or if there is a different cast or way to do this. Thanks.
EDIT: My wording is a little weird, so as an arbitrary example I'd like to somehow cast a array of 16 unsigned bytes into an array of 4 Colors.
EDIT: Also I know it's kind of a little late, but I cant seem to find how to cast a small portion of the array at a specific place to a single struct using a reinterpret_cast, if that is possible, without copying to a smaller array and casting like that. So any help with this problem would also be greatly appreciated.
Upvotes: 2
Views: 2851
Reputation: 598414
as an arbitrary example I'd like to somehow cast a array of 16 unsigned bytes into an array of 4 Colors.
Like this:
#pragma pack(push, 1)
struct Color
{
uint8 r;
uint8 g;
uint8 b;
uint8 a;
};
#pragma pack(pop)
uint8 bytearray[16];
...
Color *colorarray = reinterpret_cast<Color*>(bytearray);
Then you can do things like this:
for (int idx = 0; idx < 4; ++idx)
{
Color &c = colorarray[idx];
// use c.r, c.g, c.b, c.a as needed...
}
Upvotes: 6