You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将std::uint64_t编码为std::vector<float>进行传递?

实现uint64_t与vector的双向转换

核心思路是利用32位float的位存储能力,将64位的std::uint64_t拆分为两个32位无符号整数,再通过按位复制的方式将这两个整数转换为float(仅保留位模式,不做数值转换)存入std::vector<float>;还原时反向操作即可。

实现代码

#include <cstdint>
#include <vector>
#include <cstring>
#include <type_traits>

// 静态断言确保平台类型尺寸符合预期
static_assert(sizeof(std::uint32_t) == sizeof(float), "uint32_t和float必须为32位");
static_assert(sizeof(std::uint64_t) == 2 * sizeof(std::uint32_t), "uint64_t必须为64位");

// 将uint64_t打包为vector<float>
std::vector<float> pack_uint64_to_float_vec(std::uint64_t value) {
    std::vector<float> result(2);
    
    // 拆分64位值为低32位和高32位
    std::uint32_t low_bits = static_cast<std::uint32_t>(value & 0xFFFFFFFFULL);
    std::uint32_t high_bits = static_cast<std::uint32_t>((value >> 32) & 0xFFFFFFFFULL);
    
    // 按位复制uint32_t到float,避免数值转换导致的精度丢失
    std::memcpy(&result[0], &low_bits, sizeof(float));
    std::memcpy(&result[1], &high_bits, sizeof(float));
    
    return result;
}

// 从vector<float>解包回uint64_t
std::uint64_t unpack_float_vec_to_uint64(const std::vector<float>& vec) {
    if (vec.size() != 2) {
        // 非法输入处理,可根据需求替换为异常抛出或其他逻辑
        return 0;
    }
    
    std::uint32_t low_bits, high_bits;
    
    // 将float的位模式复制回uint32_t
    std::memcpy(&low_bits, &vec[0], sizeof(std::uint32_t));
    std::memcpy(&high_bits, &vec[1], sizeof(std::uint32_t));
    
    // 拼接为64位值
    return (static_cast<std::uint64_t>(high_bits) << 32) | low_bits;
}

关键说明

  • 使用std::memcpy的原因:避免reinterpret_cast触发C++严格别名规则导致的未定义行为,memcpy是安全的按位复制方式。
  • 静态断言:提前验证平台的类型尺寸兼容性,防止在不满足条件的平台上运行时出错。
  • 拆分与拼接逻辑:低32位通过value & 0xFFFFFFFFULL直接截取,高32位通过右移32位后截取;还原时将高32位左移32位,再与低32位按位或拼接。

使用示例

#include <iostream>

int main() {
    std::uint64_t original = 0x12345678ABCDEF01ULL;
    auto packed_data = pack_uint64_to_float_vec(original);
    std::uint64_t restored_data = unpack_float_vec_to_uint64(packed_data);
    
    std::cout << std::hex << "原始值: " << original << "\n还原值: " << restored_data << std::endl;
    // 输出结果应完全一致
    return 0;
}

内容的提问来源于stack exchange,提问作者Foaly

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 16:32:35