M
ma740988
Consider the source snippet:
union to_uchar
{
int i;
unsigned int ui;
long l;
unsigned long ul;
short s;
unsigned short us;
double d;
unsigned char uc[8];
void byteSwap(int siz)
{
int idx = 0;
int jdx = siz-1;
while (idx < jdx)
{
std::swap(uc[idx], uc[jdx]);
idx++, jdx--;
}
}
to_uchar(int ii) : i(ii) { swap(i); }
to_uchar(double dd) : d(dd) { swap(d); }
unsigned char* getBuf() { return uc; }
static void swap(int& i)
{
to_uchar x = i; //[1]
x.byteSwap(sizeof(i));
i = x.i;
}
static void swap(double& d)
{
to_uchar x = d; //[2]
x.byteSwap(sizeof(d));
d = x.d;
}
};
int main()
{
double d = 12345.678;
to_uchar::swap(d);
int i = 12345;
to_uchar::swap(i);
to_uchar iuc(12345);
unsigned char* bufi = iuc.getBuf();
to_uchar duc(12345.678);
unsigned char* bufd = duc.getBuf();
}
the lines indicated by [1] and [2] above results in exceptions but this
is one of those cases where I dont fully understand why or what teh
solution is.
Thanks in advance
union to_uchar
{
int i;
unsigned int ui;
long l;
unsigned long ul;
short s;
unsigned short us;
double d;
unsigned char uc[8];
void byteSwap(int siz)
{
int idx = 0;
int jdx = siz-1;
while (idx < jdx)
{
std::swap(uc[idx], uc[jdx]);
idx++, jdx--;
}
}
to_uchar(int ii) : i(ii) { swap(i); }
to_uchar(double dd) : d(dd) { swap(d); }
unsigned char* getBuf() { return uc; }
static void swap(int& i)
{
to_uchar x = i; //[1]
x.byteSwap(sizeof(i));
i = x.i;
}
static void swap(double& d)
{
to_uchar x = d; //[2]
x.byteSwap(sizeof(d));
d = x.d;
}
};
int main()
{
double d = 12345.678;
to_uchar::swap(d);
int i = 12345;
to_uchar::swap(i);
to_uchar iuc(12345);
unsigned char* bufi = iuc.getBuf();
to_uchar duc(12345.678);
unsigned char* bufd = duc.getBuf();
}
the lines indicated by [1] and [2] above results in exceptions but this
is one of those cases where I dont fully understand why or what teh
solution is.
Thanks in advance