How does this code obtain, binary, octal and hexadecimal numbers

I got codes that shows how to obtain binary, octal and hexadecimal numbers. However, i could not understand so i need some guidance.

This is the binary representation
1
2
3
4
5
6
  n = 50; // some random numbers
  k = 32;
  for(int i = k - 1; i >= 0; i--)
  {
    cout << ((n >> 1)& 1);
  }


This is the octal representation
1
2
3
4
5
6
  n = 50; // some random numbers
  k = 11;
  for(int i = k - 1; i >= 0; i--)
  {
    cout << ((n >> 3 * i)& 1);
  }


This is the hexa representation
1
2
3
4
5
6
7
  n = 50; // some random numbers
  k = 8;
  char hexa [] = "0123456789ABCDEF";
  for(int i = k - 1; i >= 0; i--)
  {
    cout << hexa[((n >> 4 * i)& 15)];
  }
They used bitwise operators to accomplish the task. Unless the person has very good understanding of C++, he probably won't understand what these codes are trying to do.

They may speed up things quite significantly but in exchange you have to sacrifice a large portion of code readability. So I would not recommend these for daily code writing unless you are writing performance critical code.

I would rather you learn these instead.

This is the binary representation :
cout << bitset<32>(n);

This is the octal representation :
cout << oct << n;

This is the hexa representation :
cout << hex << n;

Standard headers required :
1
2
#include <bitset>
#include <iomanip> 
I do understand there's some other easier way of doing such operation. But i'm learning C++, so i'm trying to understand what the above codes mean. Hope if anyone could kindly explain the meaning of the above codes.
Last edited on
Topic archived. No new replies allowed.