Config Router

  • Google Sheets
  • CCNA Online training
    • CCNA
  • CISCO Lab Guides
    • CCNA Security Lab Manual With Solutions
    • CCNP Route Lab Manual with Solutions
    • CCNP Switch Lab Manual with Solutions
  • Juniper
  • Linux
  • DevOps Tutorials
  • Python Array
You are here: Home / Is there a printf converter to print in binary format?

Is there a printf converter to print in binary format?

October 8, 2021 by James Palmer

Hacky but works for me:
#define BYTE_TO_BINARY_PATTERN “%c%c%c%c%c%c%c%c”
#define BYTE_TO_BINARY(byte)
(byte & 0x80 ? ‘1’ : ‘0’),
(byte & 0x40 ? ‘1’ : ‘0’),
(byte & 0x20 ? ‘1’ : ‘0’),
(byte & 0x10 ? ‘1’ : ‘0’),
(byte & 0x08 ? ‘1’ : ‘0’),
(byte & 0x04 ? ‘1’ : ‘0’),
(byte & 0x02 ? ‘1’ : ‘0’),
(byte & 0x01 ? ‘1’ : ‘0’)

printf(“Leading text “BYTE_TO_BINARY_PATTERN, BYTE_TO_BINARY(byte));

For multi-byte types
printf(“m: “BYTE_TO_BINARY_PATTERN” “BYTE_TO_BINARY_PATTERN”n”,
BYTE_TO_BINARY(m>>8), BYTE_TO_BINARY(m));

You need all the extra quotes unfortunately. This approach has the efficiency risks of macros (don’t pass a function as the argument to BYTE_TO_BINARY) but avoids the memory issues and multiple invocations of strcat in some of the other proposals here.

Print Binary for Any Datatype
// Assumes little endian
void printBits(size_t const size, void const * const ptr)
{
unsigned char *b = (unsigned char*) ptr;
unsigned char byte;
int i, j;

for (i = size-1; i >= 0; i–) {
for (j = 7; j >= 0; j–) {
byte = (b[i] >> j) & 1;
printf(“%u”, byte);
}
}
puts(“”);
}

Test:
int main(int argv, char* argc[])
{
int i = 23;
uint ui = UINT_MAX;
float f = 23.45f;
printBits(sizeof(i), &i);
printBits(sizeof(ui), &ui);
printBits(sizeof(f), &f);
return 0;
}

Related

Filed Under: Uncategorized

Recent Posts

  • How do I give user access to Jenkins?
  • What is docker volume command?
  • What is the date format in Unix?
  • What is the difference between ARG and ENV Docker?
  • What is rsync command Linux?
  • How to Add Music to Snapchat 2021 Android? | How to Search, Add, Share Songs on Snapchat Story?
  • How to Enable Snapchat Notifications for Android & iPhone? | Steps to Turn on Snapchat Bitmoji Notification
  • Easy Methods to Fix Snapchat Camera Not Working Black Screen Issue | Reasons & Troubleshooting Tips to Solve Snapchat Camera Problems
  • Detailed Procedure for How to Update Snapchat on iOS 14 for Free
  • What is Snapchat Spotlight Feature? How to Make a Spotlight on Snapchat?
  • Snapchat Hack Tutorial 2021: Can I hack a Snapchat Account without them knowing?

Copyright © 2025 · News Pro Theme on Genesis Framework · WordPress · Log in