masking out unwanted bits in c

Given the decimal 71744474 in binary it is 0100010001101011101111011010 what I am trying to extract from this decimal is every seven bits starting from the lower bits. Each of the seven bits are to represent a printable ASCII character which can only have 7 bits. In total I am pulling out four characters. The first character is 1011010 which is Z in ASCII. The next character is w and so on. I am thinking there is a way to mask out the bits I care about some how.


Use bitwise operators:

0100010001101011101111011010 & 0000000000000000000001111111 = 1011010

To get the second character, do

0100010001101011101111011010 & 0000000000000011111110000000

and so on..


Something along the lines of this should suffice:

#include <stdio.h>

int main (void) {
    unsigned int value = 71184592; // Secret key :-)

    for (unsigned int shift = 0; shift < 28; shift += 7)
        printf ("%c", (value >> shift) & 0x7f);
    putchar ('n');

    return 0;
}

It uses bit shifting get the specific bits you want into the least significant seven bits of the value, and bit masking to clear out all other bits.

If you run that code, you'll see it can quite happily extract the individual ASCII characters in groups of seven bits each:

Pax!

int myN  = 71744474;
int mask = 0x7F7F7F7F; // 7F is 0111 1111, or 7 on bits.

int result = myN & mask;

char myBytes[4];
myBytes[0] = (char)((result        & 0x000000FF);
myBytes[1] = (char)((result >>  8) & 0x000000FF);
myBytes[2] = (char)((result >> 16) & 0x000000FF);
myBytes[3] = (char)((result >> 24) & 0x000000FF);


// Now, examine myBytes[0-3], and I think they'll be what you want.
链接地址: http://www.djcxy.com/p/72608.html

上一篇: 64位有符号乘法

下一篇: 屏蔽c中不需要的位