int to char array conversion

I need to convert an integer into array of chars:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

unsigned int ret_num()
{
return 112;
}


int main()
{

unsigned char *dest=new unsigned char[4];
memcpy(dest,(char*)ret_num(),4); // something goes wrong here
delete[]dest;

}

I tried but it doesn't work (I think I've done this before but I forgot how...). Any ideas?
Thanks for help!
You're converting an integer to a pointer. memcpy() will try to read what's at 0x00000070.
Endian-unsafe:
1
2
3
4
5
union int_bytes
  {
  unsigned char chars[ 4 ];
  unsigned int  value;
  };
1
2
3
4
5
int_bytes b;
b.value = 112;
for (unsigned n = 0; n < 4; n++)
  cout << b.chars[ 0 ] << "  ";
cout << "\n";

Endian-safe:
1
2
3
4
5
#ifdef __WIN32__
  #include <winsock2.h>
#else
  #include <arpa/inet.h>
#endif 
1
2
3
4
5
6
7
8
9
10
11
12
int_bytes b;
b.value = htonl( 112 );

cout << "big-endian order: ";
for (unsigned n = 0; n < 4; n++)
  cout << b.chars[ n ] << " ";
cout << "\n\n";

cout << "little-endian order: ";
for (unsigned n = 4; n > 0;)
  cout << b.chars[ --n ] << " ";
cout << "\n";

You'll have to link with the appropriate network library. (Or write your own version of htonl().)

Hope this helps.
Topic archived. No new replies allowed.