I saw in beej network guide some code that packs a int into a char and I didnt understand some things about it so I was just playing around with it and for one reason or another I moved the snippet directly into main. I found out it doesn't work right when I do that. Notice it outputs a really big number if I do the operations of the pack functions in main. Any particular reason why?
#include <iostream>
#include <bitset>
#include <limits>
using namespace std;
void packi32(unsigned char *buf, unsigned long i)
{
*buf++ = i>>24;
*buf++ = i>>16;
*buf++ = i>>8;
*buf++ = i;
//cout << buf[0] << " " << buf[1] << " " << buf[2] << " " << buf[3] << endl;
}
unsigned long unpacki32(unsigned char *buf)
{
return (buf[0]<<24) | (buf[1]<<16) | (buf[2]<<8) | buf[3];
}
int main()
{
unsigned char * buf = new unsigned char[4];
unsigned long i = 254;
unsigned long result = 0;
*buf++ = i >> 24;
*buf++ = i >> 16;
*buf++ = i >> 8;
*buf++ = i;
result = unpacki32(buf);
cout << result << endl;
memset(buf, 0, sizeof(buf));
packi32(buf, i);
result = unpacki32(buf);
cout << result;
cin.get();
}