Search code examples
c++hexmidiuint32-t

Split parts of a uint32_t hex value into smaller parts in C++


I have a uint32_t as follows:

uint32_t midiData=0x9FCC00;

I need to separate this uint32_t into smaller parts so that 9 becomes its own entity, F becomes its own entity, and CC becomes its own entity. If you're wondering what I am doing, I am trying to break up the parts of a MIDI message so that they are easier to manage in my program.

I found this solution, but the problem is I don't know how to apply it to the CC section, and that I am not sure that this method works with C++.

Here is what I have so far:

uint32_t midiData=0x9FCC00;

uint32_t status = 0x0FFFFF & midiData; // Retrieve 9
uint32_t channel = (0xF0FFFF & midiData)>>4; //Retrieve F
uint32_t note = (0xFF00FF & midiData) >> 8; //Retrieve CC

Is this correct for C++? Reason I ask is cause I have never used C++ before and its syntax of using the > and < has always confused me (thus why I tend to avoid it).


Solution

  • You can use bit shift operator >> and bit masking operator & in C++ as well. There are, however, some issues on how you use it:

    Operator v1 & v2 gives a number built from those bits that are set in both v1 and v2, such that, for example, 0x12 & 0xF0 gives 0x10, not 0x02. Further, bit shift operator takes the number of bits, and a single digit in a hex number (which is usually called a nibble), consists of 4 bits (0x0..0xF requires 4 bits). So, if you have 0x12 and want to get 0x01, you have to write 0x12 >>4. Hence, your shifts need to be adapted, too:

    #define BITS_OF_A_NIBBLE 4
    
    unsigned char status = (midiData & 0x00F00000) >> (5*BITS_OF_A_NIBBLE);
    unsigned char channel = (midiData & 0x000F0000) >> (4*BITS_OF_A_NIBBLE);
    unsigned char note = (midiData & 0x0000FF00) >> (2*BITS_OF_A_NIBBLE);
    unsigned char theRest = (midiData & 0x000000FF);