Search code examples
javac++portingreinterpret-cast

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* buffer, 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?


Solution

  • 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 ...