简体   繁体   English

C:获取最高有效位和最低有效位

[英]C: Getting the most significant and least significant bits

I am given a 32-bit unsigned integer and I am trying to save the 8 most significant bits from that unsigned integer into an unsigned char.我得到了一个 32 位无符号 integer,我试图将无符号 integer 中的 8 个最高有效位保存到一个无符号字符中。 I then want to clear those bits to 0s.然后我想将这些位清除为 0。 That last part can be done with a mask but I am unsure of how exactly to find the 8 most significant bits and then having the mask know exactly which bits to clear.最后一部分可以用掩码完成,但我不确定如何准确找到 8 个最高有效位,然后让掩码确切知道要清除哪些位。

Another related problem is that I am trying to find the least significant bit and shift it to the left to make it the most significant and return that value.另一个相关的问题是我试图找到最低有效位并将其向左移动以使其成为最高有效位并返回该值。 Like above I am unsure on how to find the least significant bit and then know how far to shift it to the left像上面一样,我不确定如何找到最低有效位,然后知道将其向左移动多远

You can write two general functions one of which return the specified byte of an object of the type unsigned character and other returns a number with cleared bits of the number used as an argument.您可以编写两个通用函数,其中一个返回无符号字符类型的 object 的指定字节,另一个返回一个数字,该数字的位已清除,用作参数。

Here is a demonstrative program.这是一个演示程序。

#include <stdio.h>
#include <limits.h>

unsigned char extract_byte( unsigned int x, size_t n )
{
    n %= sizeof( x );

    return  x >> CHAR_BIT * n & 0xFF;
}

unsigned int clear_byte( unsigned int x, size_t n )
{
    n %= sizeof( x );

    return x & ~( 0xFF << n * CHAR_BIT );
}

int main(void) 
{
    unsigned int x = 0x04030201;

    for ( size_t i = 0; i < sizeof( x ); i++ )
    {
        printf( "%hhu ", extract_byte( x, i ) );
    }
    putchar( '\n' );

    for ( size_t i = 0; i < sizeof( x ); i++ )
    {
        printf( "%#x ", x = clear_byte( x, i ) );
    }
    putchar( '\n' );

    return 0;
}

Its output is它的 output 是

1 2 3 4 
0x4030200 0x4030000 0x4000000 0 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM