How does this reinterpret_cast work? (Porting C++ to Java)
I have some C++ code I'm trying to port to Java, that looks like this:
struct foostruct {
unsigned char aa : 3;
bool ab : 1;
unsigned char ba : 3;
bool bb : 1;
};
static void foo(const unsigned char* b开发者_开发知识库uffer, int length)
{
const unsigned char *end = buffer + length;
while (buffer < end)
{
const foostruct bar = *(reinterpret_cast<const foostruct*>(buffer++));
//read some values from struct and act accordingly
}
}
What is the reinterpret_cast
doing?
its basically saying the 8 bits represented at the current pointer should be interpreted as a "foostruct".
In my opinion it would be better written as follows:
const unsigned char aa = *buffer & 0x07;
const bool ab = (*buffer & 0x08) != 0;
const unsigned char ba = (*buffer & 0x70) >> 4;
const bool bb = (*buffer & 0x80) != 0;
I think it is far more obvious what is being done then. I think you may well find it easier to port to Java this way too ...
It does what a classic C-style (const foostruct *)buffer
would do at worst: tells C++ to ignore all safety and that you really know what you are doing. In this case, that the buffer
actually consists of foostruct
s, which in turn are bit fields overlain on single 8 bit characters. Essentially, you can do the same in Java by just getting the bytes and doing the shift and mask operations yourself.
you have a pointer to unsigned char right? Now imagine that the bits pointed to by the pointer are treated as though it were an object of type foostruct. That's what reinterpret_cast does - it reinterprets the bit pattern to be a memory representation of another type...
精彩评论