Convert a char to a binary string representation


/ Published in: C++
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #include <stdio.h>
  2. #include <limits.h>
  3.  
  4. // Convert a char to a binary string representation of that char value
  5.  
  6. char* chartobin ( unsigned char c )
  7. {
  8. static char bin[CHAR_BIT + 1] = { 0 };
  9. int i;
  10.  
  11. for ( i = CHAR_BIT - 1; i >= 0; i-- )
  12. {
  13. bin[i] = (c % 2) + '0';
  14. c /= 2;
  15. }
  16.  
  17. return bin;
  18. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.