c - How to ignore bits in a variable -
i know how delete bits in bit value.
i receive 10 bits value (bit 0 bit 9) , have send variable ignore bit 0, bit 2, bit 4 , bit 6 of received value variable : bit 987531. how can ? heard mask bit don't know how use if know mask 0x55
thank helping me
a solution uses 5 bits be
new_value = ((data & 0x002) >> 1) | ((data & 0x008) >> 2) | ((data & 0x020) >> 3) | ((data & 0x080) >> 4) | ((data & 0x200) >> 5);
but here solution instead of using fixed number of bits (i.e. 5 in case) uses function allows specify number of bits keep.
it like:
#include <stdio.h> #include <stdlib.h> unsigned keepoddbits(const unsigned data, const unsigned number_of_bits_to_keep) { unsigned new_value = 0; unsigned mask = 0x2; int i; (i=0; < number_of_bits_to_keep; ++i) { if (mask & data) { new_value = new_value | ((mask & data) >> (i + 1)); } mask = mask << 2; } return new_value; } int main() { printf("data 0x%x becomes 0x%x\n", 0x3ff, keepoddbits(0x3ff, 5)); printf("data 0x%x becomes 0x%x\n", 0x2aa, keepoddbits(0x2aa, 5)); printf("data 0x%x becomes 0x%x\n", 0x155, keepoddbits(0x155, 5)); return 0; }
will output:
data 0x3ff becomes 0x1f data 0x2aa becomes 0x1f data 0x155 becomes 0x0
changing main
request 3 instead of 5 bits, like:
int main() { printf("data 0x%x becomes 0x%x\n", 0x3ff, keepoddbits(0x3ff, 3)); printf("data 0x%x becomes 0x%x\n", 0x2aa, keepoddbits(0x2aa, 3)); printf("data 0x%x becomes 0x%x\n", 0x155, keepoddbits(0x155, 3)); return 0; }
will output:
data 0x3ff becomes 0x7 data 0x2aa becomes 0x7 data 0x155 becomes 0x0
Comments
Post a Comment