I'm working on a homework assignment to print out big and little endian values of an int
and float
. I'm having trouble converting to little endian.
here's my code
void convertLitteE(string input)
{
int theInt;
stringstream stream(input);
while(stream >> theInt)
{
float f = (float)theInt;
printf("\n%d\n",theInt);
printf("int: 0x");
printLittle((char *) &theInt, sizeof(theInt));
printf("\nfloat: 0x");
printLittle((char *) &f, sizeof(f));
printf("\n\n");
}
}
void printLittle(char *p, int nBytes)
{
for (int i = 0; i < nBytes; i++, p++)
{
printf("%02X", *p);
}
}
when input is 12 I get what I would expect
output:
int: 0x0C000000
float: 0x00004041
but when input is 1234
output:
int: 0xFFFFFFD20400000
float: 0x0040FFFFFFF9A44
but I would expect
int : 0xD2040000
float: 0x00409A44
When I step through the for
loop I can see where there appears to be a garbage value and then it prints all the F
's but I don't know why. I've tried this so many different ways but I can't get it to work.
Any help would be greatly appreciated.
convertLitteE
is supposed to convert from a decimal string to little-endian hexadecimal output. No fundamental issue with that part. – ascheplerint
, one by one. That is not guaranteed to give you a little-endian integer representation. It will give you whatever representation your system uses for integers. – jogojapan