Masking unwanted bits in c

Given the decimal number 71744474 in binary format, this is 0100010001101011101111011010 , what I am trying to extract from this decimal number is every seven bits, starting with the least significant bits. Each of the seven bits must be a printable ASCII character, which may contain only 7 bits. In total, I pull out four characters. The first character is 1011010 , which is Z in ASCII. The next character is w and so on. I think there is a way to mask the bits that I like.

+4
source share
4 answers

Use bitwise operators:

 0100010001101011101111011010 & 0000000000000000000001111111 = 1011010 

To get the second character, do

 0100010001101011101111011010 & 0000000000000011111110000000 

etc.

+7
source

Something along the lines of this should be enough:

 #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 offsets to get the specific bits you want into the least significant seven bits of the value, and bit masking to clear all other bits.

If you run this code, you will see that it can very well extract individual ASCII characters in groups of seven bits:

 Pax! 
+3
source
 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. 
+2
source
 #include <stdio.h> int main() { int a = 71744474; a = a&0xFFFFFFF; // 1111111 1111111 1111111 1111111 while (a>0) { char b = a&0x7f; // 1111111 printf("%c", b); a = a>>7; } } 
0
source

Source: https://habr.com/ru/post/1342078/


All Articles