3

我有一个无符号整数值

u_int_variable = 43981; // This is equal to ABCD in HEX

我可以使用 ABCD 将其打印到十六进制控制台

printf("Value in Hex is %X", u_int_variable);

// Output : Value in Hex is ABCD

我怎样才能转换和分离这个

unsigned char uhex, lhex;

uhex = 0xAB; and lhex = 0xCD;
4

3 回答 3

2
uhex = static_cast<unsigned char>(u_int_variable >> 8);
lhex = static_cast<unsigned char>(u_int_variable & 0xFF);

或者,对于 >32 位无符号整数绝对安全:

uhex = static_cast<unsigned char>((u_int_variable >> 8) & 0xFF);
于 2012-11-09T09:36:10.790 回答
1

作为变体:

unsigned char uhex, lhex;
lhex = static_cast<unsigned char>( u_int_variable & 0xFF );
uhex = static_cast<unsigned char>( (u_int_variable >> 8) & 0xFF );

关于按位运算的好的第一深度文章在这里

于 2012-11-09T09:36:19.380 回答
1

我让你使用位域联合,解决方案看起来像这样:

struct hex
    {
        unsigned int lhex : 8; // upper and lower part alignement are system dependent
        unsigned int uhex : 8;
    };

    union number
    {
        number(int val): m_val(val){};
        void lhex(void) {printf("lhex %X", this->num.lhex);};
        void uhex(void) {printf("uhex %X", this->num.uhex);};
        int m_val;
        hex num;
    };

    number n(43981);
    n.lhex();
    n.uhex();
于 2012-11-09T09:49:13.427 回答