Converting uint64_t to char* in C++

This article demonstrates how to convert a uint64_t (unsigned 64-bit integer) to a char* string representing its binary representation.

Understanding the Challenge

Since uint64_t is an unsigned integer, converting it to a char* requires considering the length of its binary representation. The following C++ code provides a solution:

#include <cstdint>
#include <cstring>

void uint64_to_char(uint64_t num, char* str) {
    // Store binary representation of num in buf
    char buf[65] = {0};
    for (int i = 0; i < 64; ++i) {
        buf[63-i] = ((num >> i) & 1) + '0';
    }

    // Find the first non-zero position
    int pos = 0;
    while (pos < 64 && buf[pos] == '0') {
        ++pos;
    }

    // Copy content from buf to str
    int len = 64 - pos;
    memcpy(str, buf + pos, len);
    str[len] = '\0';
}

Usage Example:

#include <iostream>

int main() {
    uint64_t num = 123456789;
    char str[65];
    uint64_to_char(num, str);
    std::cout << str << std::endl;  // Output: '000000000000000111010110111100110011010001011000101100101'
    return 0;
}

Explanation:

  1. uint64_to_char function:

    • The function takes a uint64_t value (num) and a char* pointer (str) as input.
    • It creates a buf array of size 65 to store the binary representation.
    • The for loop iterates through each bit of the num and sets the corresponding character in buf to '0' or '1'.
    • The while loop finds the starting position of the non-zero bits.
    • memcpy copies the relevant portion of buf to str and adds a null terminator.
  2. main function:

    • It initializes a uint64_t variable (num) with the value 123456789.
    • It declares a char array str to store the converted binary representation.
    • It calls the uint64_to_char function to perform the conversion.
    • Finally, it prints the str to the console.

This C++ code provides a practical and efficient way to convert a uint64_t to its binary representation stored in a char* string. You can use this code as a starting point for manipulating and analyzing binary data within your C++ programs.

uint64_t to char* Conversion: C++ Code Example

原文地址: https://www.cveoy.top/t/topic/np4S 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录