uint64_t to char* Conversion: C++ Code Example
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:
-
uint64_to_charfunction:- The function takes a
uint64_tvalue (num) and achar*pointer (str) as input. - It creates a
bufarray of size 65 to store the binary representation. - The
forloop iterates through each bit of thenumand sets the corresponding character inbufto '0' or '1'. - The
whileloop finds the starting position of the non-zero bits. memcpycopies the relevant portion ofbuftostrand adds a null terminator.
- The function takes a
-
mainfunction:- It initializes a
uint64_tvariable (num) with the value 123456789. - It declares a
chararraystrto store the converted binary representation. - It calls the
uint64_to_charfunction to perform the conversion. - Finally, it prints the
strto the console.
- It initializes a
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.
原文地址: https://www.cveoy.top/t/topic/np4S 著作权归作者所有。请勿转载和采集!