顺便说一句,你的代码可以很好地与GCC 4.7在Debian/GNU/Linux/x86-64调用
uint32_t r,g,b;
r = (uint32_t)145;
g = (uint32_t)131;
b = (uint32_t)139;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
float rgbf = *reinterpret_cast<float*>(&rgb);
uint32_t rgbnew = *(reinterpret_cast<uint32_t *>(&rgbf));
uint8_t rnew = (rgbnew >> 16) & 0x0000ff;
uint8_t gnew = (rgbnew >> 8) & 0x0000ff;
uint8_t bnew = (rgbnew) & 0x0000ff;
当我尝试运行这段代码时,在
行有分段错误RGB = ((uint32_t)r <<16 | (uint32_t)g <<8 | (uint32_t)b);
事实上,在一个地方它运行正常。
请尝试编译带有所有警告和调试信息的代码(例如Linux上的g++ -Wall -g
)并改进它直到没有警告。学习使用调试器(即Linux上的gdb
)
我猜故障可能在
float rgbf = *reinterpret_cast<float*>(&rgb);
,因为如果rgb
(即uint32_t
)和float
没有相同的对齐或大小约束,这可能会触发故障。某些系统(处理器、abi、编译器)可能有不同的&不兼容的约束
顺便说一句,你的代码可以很好地与GCC 4.7在Debian/GNU/Linux/x86-64调用
g++-4.7 -std=c++11 -Wall -g ramji.cc -o ramji
当我有
#include <cstdint>
#include <iostream>
int main(int argc, char**argv)
{
uint32_t r,g,b;
r = (uint32_t)145;
g = (uint32_t)131;
b = (uint32_t)139;
std::cout << "r=" << r << " g=" << g << " b=" << b << std::endl;
uint32_t rgb = ((uint32_t)r << 16 | (uint32_t)g << 8 | (uint32_t)b);
std::cout << "rgb=" << rgb << std::endl;
float rgbf = *reinterpret_cast<float*>(&rgb);
std::cout << "rgbf=" << rgbf << std::endl;
uint32_t rgbnew = *(reinterpret_cast<uint32_t *>(&rgbf));
std::cout << "rgbnew=" << rgb << std::endl;
uint8_t rnew = (rgbnew >> 16) & 0x0000ff;
uint8_t gnew = (rgbnew >> 8) & 0x0000ff;
uint8_t bnew = (rgbnew) & 0x0000ff;
std::cout << "rnew=" << rnew << " gnew=" << gnew
<< " bnew=" << bnew << std::endl;
return 0;
}
没有警告,执行时没有崩溃。
注意<cstdint>
需要c++ 11兼容的编译器