Search code examples
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

    • Bitshift: a[0] << 4 means move every bit to the left 4 times so 0b00001011 becomes 0b10110000 (bits coming into the right default as 0)
    • Bitwise OR: a[0] << 4 | a[1], the | compares every bit from a[0] with a[1]. If either on of the bits are 1's it gives a 1, if both are 0, it gives a 0 i.e.

      10110000 | 00001111 = 10111111

    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.