Posted By

zava on 08/16/10


Tagged

textmate bit field


Versions (?)

bit field


 / Published in: C
 

  1. // <Pointer on C> by Kenneth A. Reek
  2. // P89
  3. // No.5
  4.  
  5. int store_bit_field(int original_value, int value_to_store, unsigned starting_bit, unsigned ending_bit)
  6. {
  7. unsigned int mask = ~0;
  8. int n_bits = sizeof(unsigned int) * 8;
  9. mask <<= (n_bits - 1 - starting_bit) ;
  10. mask >>= (n_bits - (starting_bit - ending_bit + 1));
  11. mask <<= ending_bit;
  12.  
  13. return (original_value & ~mask) | ((value_to_store << ending_bit) & mask);
  14. }
  15.  
  16. int main (int argc, char const *argv[])
  17. {
  18. printf("%xn", store_bit_field(0x0, 0x1, 4, 4));
  19. printf("%xn", store_bit_field(0xffff, 0x123, 15, 4));
  20. printf("%xn", store_bit_field(0xffff, 0x123, 13, 9));
  21. return 0;
  22. }

Report this snippet  

You need to login to post a comment.