从Hex获取LSB的值(C代码)

时间:2010-06-09 12:24:29

标签: c++ c bit-manipulation bit-shift

我在C中有这样的代码:

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

我需要提取它,使得最终值为:

0xa1df7

如果十六进制值至少为零,我只能提取并使其工作:

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

使用以下代码:

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;
}

似乎最后一个{...}块对我来说很麻烦。有任何想法吗?谢谢!

4 个答案:

答案 0 :(得分:5)

#include <stdio.h>
#include <stdlib.h>

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

int main(int argc, char*argv[]){
    int i,r = 0;
    for(i=0; i<sizeof(data); i++){
        if(data[i] & 0xf0) r = (r<<4) + (data[i]>>4);
        if(data[i] & 0x0f) r = (r<<4) + (data[i]&0x0f);
    }
    printf("%x\n",r);
    return 0;
}

输出“a1df7”

答案 1 :(得分:0)

你最好先将它全部转换为十六进制字符串(“0a1df007”),然后删除所有零:)

答案 2 :(得分:0)

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

 unsigned int value=0;
 for(int i=0; i<4; i++)
 {
     int nibble = (data[i] & 0xf0) >> 4;
     if(nibble > 0)
     {
          value<<=4;
          value += nibble;
     }
     nibble = data[i] & 0x0f;
     if(nibble > 0)
     {
          value<<=4;
          value += nibble;
     }
 }

答案 3 :(得分:0)

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

嗯,但这看起来像一个普通的网络字节顺序。

对于32位int,请执行以下操作:

unsigned char *p = (unsigned char *)data;
int val = (p[0]<<24) | (p[1]<<16) | (p[2]<<8) | p[3];

类似于64位值。

P.S。标志要小心。在某些情况下,需要显式转换为有符号类型才能强制进行符号位扩展。