如何从特定数字中获取值?

How can I get a value from particular number?

我有一个十六进制值 0x40BF00FF,我想从中得到这个值 0xFF(最后两个数字),其他数字被忽略。我们如何用C语言编写代码

这取决于您使用的语言版本。但要了解更多信息,您可以阅读 here

在对最后两个字符进行子字符串化之后,您可以将其与第一个字符连接起来。

解决方案

对 0x000000FF 使用位掩码:

int result = 0x000000FF & 0x40BF00FF;

完整代码示例

int input = 0x40BF00FF; //input example
int output = 0x000000FF & input;
printf("%04x", output); //prints result

结果

00ff

如果您有十六进制值(不是字符串)。这个小程序可以作为一个很好的例子:

此方法提取单个半字节。然后加入他们。

我们可以通过对16取模得到最低有效的4位。 然后我们可以左移4次(除以16)。然后提取下一个最低有效 4 位。

现在我们得到了 8 LSB。现在我们只是追加它们。

#include <stdio.h>

int main()
{
    unsigned int x = 0x40BF00FF;

    // Extracting the first 4 least significant bits.
    unsigned int one = x % 16;

    // Extracting the next 4 least significant bits.
    unsigned int two = (x >> 4) % 16;

    // Appending the bits and printing the result.
    printf ("%x\n", (two << 4) + one);

    return 0;
}

你可以使用比特的力量!

在这里,输入存储在x中。

我戴口罩0xFF

然后我执行按位与操作。

现在,我们知道

b&1 = bb&0 = 0

我们可以使用这个属性通过将它们全部设置为1而将其他设置为0来仅提取低8位。 并执行按位与 (&)。

#include <stdio.h>

int main()
{
    unsigned int x = 0x40BF00FF;

    // The mask.
    unsigned int mask = 0xFF;

    // Applying bitwise and
    printf ("%x\n", x & mask);

    return 0;
}
uint8_t get8bits(uint32_t value, int byteNumber) 
{
 uint8_t bitShift = byteNumber * 8;
 uint32_t mask = 0xfful << byteShift;

 return (value & mask) >> bitShift;
}