c++avratmega16

how can merge one array values in one integer c++


How can i merge one array values in one integer and upside down?

example: a[]=0b1011,0b1111 to 10111111 and 10010101 to b[]=0b1001,0b0101

Solution

  • You need to covert types so that the values so they can hold 8 bits (a char or uint8 would do depending on what you need). I'm not sure what type you have there as its 4 bits. You're better off redefining the type to be a uint8 or something so a[0] = 0b00001011.

    Once you have the right number of bits need to bitshift the first value left by 4, then use the bitwise OR operator, taking your example,

    int8 myValue = a[0] << 4 | a[1]
    

    Here's whats going on

    By upside down I assume you mean in reverse?

    You'll need to use the bitwise AND &, and do something similar so I wont explain in detail again, but its this

    a[0] = (myValue & 0b1111000) >> 4 = 00001011
    
    a[1] = myValue & 0b00001111 = 00001111
    

    Hope that helps.