Skip to content
Related Articles

Related Articles

Improve Article

CHAR_BIT in C

  • Difficulty Level : Medium
  • Last Updated : 28 Oct, 2017

CHAR_BIT : It is the number of bits in char. These days, almost all architectures use 8 bits per byte (But it is not the case always, some older machines used to have 7-bit byte). It can be found in

Let us see an application of it. Suppose we wish to print byte by byte representation of an integer.

Examples :

Input  : 4
Output : 00000000 00000000 00000000 00000100

Input  : 12
Output : 00000000 00000000 00000000 00001100 




// CPP program to print byte by byte presentation
#include <bits/stdc++.h>
using namespace std;
  
// function in which number and intitally 0 is passed
void printInBinary(int num)
{
    int n = CHAR_BIT*sizeof(num);
    stack<bool> s;
    for (int i=1; i<=n; i++)
    {
        s.push(num%2);
        num = num/2; 
    }     
    for (int i=1; i<=n; i++)
    {
        cout << s.top();
        s.pop();
          
        // Put a space after every byte. 
        if (i % CHAR_BIT == 0)
        cout << " "
    }
}
  
int main()
{
    int num = 12;
    printInBinary(num);
    return 0;
}

Output :

00000000 00000000 00000000 00001100 

This article is contributed by Apurva Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.
My Personal Notes arrow_drop_up
Recommended Articles
Page :