How to undo the bitmap section in C?

In short, if I am dealing with a binary number, for example 0000 0110 , and suppose I want only the last 3 bits to be canceled, are there any methods that translate this to 0000 0011 ?

I saw other questions and resources that implement the reverse bits method , but return the integer the opposite (i.e. 0110 0000 , not 0000 0011 ).

Is it enough to simply cancel it, as is done in standard methods, and then shift it as much as necessary? Or is there a more direct way to achieve this?

Format: unsigned int reverse_select_bits(int number, int num_bits) { ... }

+4
source share
3 answers

Simple link

See http://graphics.stanford.edu/~seander/bithacks.html#BitReverseObvious - this is a good start for you to see how it really should be done. There are some pretty interesting methods here. Especially take a look at

http://graphics.stanford.edu/~seander/bithacks.html#ReverseByteWith64Bits

to understand how to think about these issues.

TIP A

For an arbitrary word size, use the obvious method after using the mask to mask the bit you want to keep:

 typeof(word) preserve_mask = \ ((1 << 8*sizeof(word)) - 1) & ~(typeof(word))((1 << K) - 1); 

Where K is the number of bits you want to flip. preserve_mask will give you a mask to save part of the word that you do not want to flip. Please note that the above is not C code, but a concept that you must implement. I suggest first doing this within your processor; and then process arbitrary precision later (and only if necessary).

Tip B

Can you see how this can be done for an arbitrary length using the ReverseByteWith64Bits generalization?

Is it possible to execute a piece of food on N bits, where N ≢ 0 (mod 8)? can you use the result from hint A?

Let me know if you need more help.

+1
source

Since you only need to cancel the three bits, preparing a table of eight records is the easiest way to do this.

 int rev_table[8] = {0, 4, 2, 6, 1, 5, 3, 7}; int rev_last_three_bits(int v) { return (v & (~7)) | rev_table[v&7]; } 
0
source

A function has been implemented that can exchange two specific bits in char.

You can undo any section of bits using this function.

 #include<stdio.h> void swap_bits(char *a,unsigned char p1,unsigned char p2) { if (p1==p2) return;//don't need swap unsigned char bit1=(1<<p1)&(*a);//access the bit in position 1(0-indexed); unsigned char bit2=(1<<p2)&(*a);//access the bit in position 2(0-indexed); (*a)^=bit1;//set the bit in position 1 to 0. if (bit2) (*a)^=1<<p1;// if bit2 is 1 then set the bit in position to 1 (*a)^=bit2; if (bit1) (*a)^=1<<p2; } int main() { char a=0x06; swap_bits(&a,0,2); printf("%x\n",a); } 
-1
source

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


All Articles