gpt4 book ai didi

c++ - 将指针转换为 float ?

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:24:25 25 4
gpt4 key购买 nike

我有一个unsigned char*。通常这指向一大块数据,但在某些情况下,指针是数据,即。将 int 值转换为 unsigned char* 指针 (unsigned char* intData = (unsigned char*)myInteger;),反之亦然。

但是,我需要使用 float 值来执行此操作,但它一直给我转换错误。

unsigned char* data;
float myFloat = (float)data;

我该怎么做?

最佳答案

位播:

template <class Dest, class Source>
inline Dest bit_cast(Source const &source) {
static_assert(sizeof(Dest)==sizeof(Source), "size of destination and source objects must be equal");
static_assert(std::is_trivially_copyable<Dest>::value, "destination type must be trivially copyable.");
static_assert(std::is_trivially_copyable<Source>::value, "source type must be trivially copyable");

Dest dest;
std::memcpy(&dest, &source, sizeof(dest));
return dest;
}

用法:

char *c = nullptr;
float f = bit_cast<float>(c);
c = bit_cast<char *>(f);

关于c++ - 将指针转换为 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12397432/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com