是否有一种编程方式来检测您是否在大端或小端架构上?我需要能够编写将在Intel或PPC系统上执行的代码并使用完全相同的代码(即没有条件编译).
从其他StackOverflow问题和ISO/IEC草案C++标准标准的§9.5.1中可以看出,使用联合来执行文字reinterpret_cast数据是未定义的行为.
请考虑以下代码.目标是取整数值,0xffff并将其解释为IEEE 754浮点中的一系列位.(二进制转换直观地显示了这是如何完成的.)
#include <iostream>
using namespace std;
union unionType {
int myInt;
float myFloat;
};
int main() {
int i = 0xffff;
unionType u;
u.myInt = i;
cout << "size of int " << sizeof(int) << endl;
cout << "size of float " << sizeof(float) << endl;
cout << "myInt " << u.myInt << endl;
cout << "myFloat " << u.myFloat << endl;
float theFloat = *reinterpret_cast<float*>(&i);
cout << …Run Code Online (Sandbox Code Playgroud) 我正在尝试阅读PNG文件的内容.
您可能知道,所有数据都以4字节方式写入png文件,包括文本和数字.因此,如果我们有数字35234,则以这种方式保存:[1000] [1001] [1010] [0010].
但有时数字较短,所以第一个字节为零,当我读取数组并将其从char*转换为整数时,我得到错误的数字.例如,[000]有时将数字误解为负数,将simetimes误解为零!
让我给你一个直观的例子:
char s_num[4] = {120, 80, 40, 1};
int t_num = 0;
t_num = int(s_num);
Run Code Online (Sandbox Code Playgroud)
我希望我能很好地解释我的问题!
如何将这些数组转换为单个整数值?
好吧好吧,让我更改我的代码来更好地解释它:
char s_num[4] = {0, 0, 0, 13};
int t_num;
t_num = *((int*) s_num);
cout << "t_num: " << t_num << endl;
Run Code Online (Sandbox Code Playgroud)
在这里我们必须得到13作为结果,好吗?但是再次使用这个新解决方案,答案是错误的,您可以在您的计算机上进行测试!我得到这个号码:218103808这绝对是错的!
考虑以下结构:
struct vec4
{
union{float x; float r; float s};
union{float y; float g; float t};
union{float z; float b; float p};
union{float w; float a; float q};
};
Run Code Online (Sandbox Code Playgroud)
像这样的东西似乎比如可以应用于GLM提供GLSL般的类型,如vec4,vec2等.
但是,尽管预期的用途是使这成为可能
vec4 a(1,2,4,7);
a.x=7;
a.b=a.r;
Run Code Online (Sandbox Code Playgroud)
,它似乎是一个未定义的行为,因为,如这里引用的,
在联合中,最多一个数据成员可以在任何时间处于活动状态,也就是说,最多一个数据成员的值可以随时存储在并集中.
例如,使用仅仅定义类似下面的结构不是更好吗?
struct vec4
{
float x,y,z,w;
float &r,&g,&b,&a;
float &s,&t,&p,&q;
vec4(float X,float Y,float Z,float W)
:x(X),y(Y),z(Z),w(W),
r(x),g(y),b(z),a(w),
s(x),t(y),p(z),q(w)
{}
vec4()
:r(x),g(y),b(z),a(w),
s(x),t(y),p(z),q(w)
{}
vec4(const vec4& rhs)
:x(rhs.x),y(rhs.y),z(rhs.z),w(rhs.w),
r(x),g(y),b(z),a(w),
s(x),t(y),p(z),q(w)
{}
vec4& operator=(const vec4& rhs)
{ …Run Code Online (Sandbox Code Playgroud) 有没有办法在不使用任何外部库(Boost等)的情况下将std :: bitset <64>转换为double?我使用bitset来表示遗传算法中的基因组,我需要一种方法将一组位转换为double.
通过遵循经验法则更喜欢static_cast或dynamic_cast在其他一切之前,我编写了以下程序:
int main(void)
{
int i = 0;
unsigned *j = static_cast<unsigned*>(&i);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但是,它甚至没有编译:
$ g++ --std=c++11 test5.cpp
test5.cpp: In function ‘int main()’:
test5.cpp:4:44: error: invalid static_cast from type ‘int*’ to type ‘unsigned int*’
unsigned *j = static_cast<unsigned*>(&i);
^
Run Code Online (Sandbox Code Playgroud)
为什么这是错的?这种情况的正确演员是什么?