1

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?

etheros
  • 2,733
  • 2
  • 24
  • 25
  • See also http://stackoverflow.com/questions/4805058/is-there-cast-in-java-similar-to-reinterpret-cast-in-c – Raedwald Mar 24 '16 at 09:42

3 Answers3

4

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 foostructs, 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.

Pontus Gagge
  • 17,166
  • 1
  • 38
  • 51
4

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

Goz
  • 61,365
  • 24
  • 124
  • 204
  • Beware: the right-shifts are wrong (right shift by 3, 4 and 7, respectively) 'Better' is debatable... – Pontus Gagge Dec 14 '10 at 12:54
  • @Pontus: You are quite right I forgot to right shift ba. The 2 bools are NOT right shifted .. they are greater thans (as greater than returns a bool). – Goz Dec 14 '10 at 12:57
  • Ah. Correcting the correction: that's collaborative... I read what I expected to see, as usual! – Pontus Gagge Dec 14 '10 at 13:02
  • 1
    It is better to always use `!= 0` to convert to boolean. With `>` it is rather confusing. – starblue Dec 14 '10 at 13:05
  • @starblue: Just for you I changed it to != but, personally, I find it no more difficult to read, however thats me, as others obviously are your point is taken. – Goz Dec 14 '10 at 13:14
  • @Goz: It's not only for starblue. When checking whether a value is not equal `0`, it's better to test `!= 0`. – sbi Dec 14 '10 at 17:23
2

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

Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434