Getting value of LSB from Hex (C code)

Posted by Rjff on Stack Overflow See other posts from Stack Overflow or by Rjff
Published on 2010-06-09T12:24:29Z Indexed on 2010/06/09 12:32 UTC
Read the original article Hit count: 207

Filed under:
|
|

Hi - first post here :)

I've got a code like this in C:

unsigned char const data[ ] = {0x0a, 0x1d, 0xf0, 0x07};

I need to extract it such that the final value is:

0xa1df7

I have only been able to extract and get it working if the hex values that have at least 1 zero:

unsigned char const data[ ] = {0x0a, 0xd0, 0xf0, 0x07};

using the code below:

for(int i = 0; i < SIZE; ++i)
{
    tmp = data[i];
    if ( (data[i] <= 0x0F) &&  (((data[i] & 0x0F) == 0) || (data[i] & 0xF0) == 0)) // one of the hex is zero
    {
        tmp = ((tmp << 4) >> 4) << N[i];
        std::cout << "foo: " << std::hex << tmp << ":" << std::endl;    

    }
    else if ((data[i] >= 0x0F) &&  (((data[i] & 0x0F) == 0) || (data[i] & 0xF0) == 0) )
    {
        tmp = (tmp >> 4) << N[i];
        std::cout << "bar: " << std::hex << tmp << ":" << std::endl;

    }
    else
    {
        std::cout << "result: " << std::hex << result << ":" << std::endl;
        std::cout << "tmp << 8: " << std::hex << (tmp << 8)<< ":" << std::endl;
        result = result | (tmp << 8);
        std::cout << "result |= (tmp << 8): " << std::hex << result << ":" << std::endl;
    }

    result |= tmp;
    std::cout << "boo: " << std::hex << result << ":" << std::endl;
}

It seems the last else {...} block is troublesome for me. Any ideas? Thanks!

© Stack Overflow or respective owner

Related posts about c

    Related posts about bit-manipulation