由于uint64_t为无符号整型,转换为char需要考虑其二进制表示的长度。以下是将uint64_t转换为char的示例代码:

#include <cstdint>
#include <cstring>

void uint64_to_char(uint64_t num, char* str) {
    // 将num的二进制表示存储到buf中
    char buf[65] = {0};
    for (int i = 0; i < 64; ++i) {
        buf[63-i] = ((num >> i) & 1) + '0';
    }

    // 找到第一个非零的位置
    int pos = 0;
    while (pos < 64 && buf[pos] == '0') {
        ++pos;
    }

    // 将buf中的内容复制到str中
    int len = 64 - pos;
    memcpy(str, buf + pos, len);
    str[len] = '\0';
}

使用示例:

#include <iostream>

int main() {
    uint64_t num = 123456789;
    char str[65];
    uint64_to_char(num, str);
    std::cout << str << std::endl;  // 输出:"000000000000000111010110111100110011010001011000101100101"
    return 0;
}
uint64_t 转换 char

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

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