Typecast cross-platform compatability question

Hi, I'm just curious as to if the following statement could possibly be unsafe/undefined behavior/etc on certain a platform:

1
2
int number = 5;
printf("%s", (char*)&number);


It works fine on a x86 system with Windows, but I'm trying to develop the best cross-platform practices. Thanks for any help.
It's completely unsafe everywhere.
Then what is the recommended way to put a binary integer into a string? For example:

1
2
int number = 5;
cppstring.append((char*)&number, 4);


I'm assuming this is very unsafe as well? I don't see another way to do this.
Last edited on
That's safe, except for the fact that you should pass sizeof(int) as the second parameter.
However, http://en.wikipedia.org/wiki/Endianness

Using printf() is unsafe because you have no way of limiting just how far printf() will read. Maybe it will stop immediately, maybe it will stop because it tried to access memory it didn't own and the OS crashed it.
er... I guess technically that's safe but it won't print "5" like you expect. It will print the ascii code for 5 (which is ?ENQUIRY? It probably has no visual representation).

If you're trying to convert the number to a string, you're going about it all the wrong way. See this: http://cplusplus.com/articles/numb_to_text/
Topic archived. No new replies allowed.