Advertisement
Naratzul

C++ Bit's operations

Oct 6th, 2015
104
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.27 KB | None | 0 0
  1. #include <stdio.h>
  2.  
  3. void bit_off(unsigned char *byte, int bit_number) {
  4.     *byte ^= *byte &(0x80 >> bit_number);
  5. }
  6.  
  7. void bit_on(unsigned char *byte, int bit_number) {
  8.     *byte |= (0x80 >> bit_number);
  9. }
  10.  
  11. void change_bit(unsigned char* byte, int bit_number) {
  12.     *byte ^= (0x80 >> bit_number);
  13. }
  14.  
  15. void print_bit(unsigned char *byte, int bit_number) {
  16.     if ((0x80 >> bit_number) & (*byte))
  17.         printf("1");
  18.     else
  19.         printf("0");
  20. }
  21.  
  22. void print_byte(unsigned char *byte) {
  23.     for (int i = 0; i < 8; i++)
  24.         if ((0x80 >> i) & (*byte))
  25.             printf("1");
  26.         else
  27.             printf("0");
  28. }
  29.  
  30. int main() {
  31.     unsigned char byte = 'a';
  32.     int n1, n2, n3, n4;
  33.     printf("Enter the bit's numbers [0..7]: ");
  34.     scanf("%d %d %d %d", &n1, &n2, &n3, &n4);
  35.     // n1 - погасить, n2 - включить, n3 - изменить, n4 - вывести
  36.     printf("\nOriginal byte: ");
  37.     print_byte(&byte);
  38.     bit_off(&byte, n1);
  39.     printf("\nBit %d is off: ", n1);
  40.     print_byte(&byte);
  41.     bit_on(&byte, n2);
  42.     printf("\nBit %d is on: ", n2);
  43.     print_byte(&byte);
  44.     change_bit(&byte, n3);
  45.     printf("\nBit %d was changed: ", n3);
  46.     print_byte(&byte);
  47.     printf("\nBit %d = ", n4);
  48.     print_bit(&byte, n4);
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement