How to convert int to binary with leading zeros in C

1 Answer

0 votes
#include <stdio.h>
#include <stddef.h>

/*
 * Converts an unsigned integer to a binary string with leading zeros.
 * - num: The integer value to convert.
 * - bits: The exact bit width (e.g., 8, 16, 32) determining the leading zeros.
 * - buffer: Pre-allocated character array to hold the resulting string.
 * - buffer_size: Size of the buffer (must be at least bits + 1 for the null terminator).
 */
void int_to_binary(unsigned int num, int bits, char *buffer, size_t buffer_size) {
    // Ensure the buffer is large enough to hold the bits plus the null terminator
    if (buffer_size <= (size_t)bits) {
        return;
    }
    
    // Null-terminate the string at the end of the specified bit width
    buffer[bits] = '\0';
    
    // Fill the buffer from right to left (least significant bit to most significant bit)
    for (int i = bits - 1; i >= 0; i--) {
        // Extract the lowest bit and convert it to its character representation ('0' or '1')
        buffer[i] = (num & 1) ? '1' : '0';
        
        // Shift the number right by 1 bit to inspect the next position
        num >>= 1;
    }
}

int (main)(void) {
    // Define the data provided
    unsigned int num = 153;

    // 1. Convert to an 8-bit binary representation (153 fits within 8 bits: 0 to 255)
    const int bits_8 = 8;
    char bin_str_8[9]; // 8 bits + 1 for null terminator '\0'
    int_to_binary(num, bits_8, bin_str_8, sizeof(bin_str_8));

    // 2. Convert to a 16-bit binary representation to demonstrate padding
    const int bits_16 = 16;
    char bin_str_16[17]; // 16 bits + 1 for null terminator '\0'
    int_to_binary(num, bits_16, bin_str_16, sizeof(bin_str_16));

    // Output the results
    printf("Original Integer: %u\n", num);
    printf("Binary (8-bit)  : %s\n", bin_str_8);
    printf("Binary (16-bit) : %s\n", bin_str_16);

    return 0;
}


/*
run:

Original Integer: 153
Binary (8-bit)  : 10011001
Binary (16-bit) : 0000000010011001

*/

 



answered 2 days ago by avibootz
...