how to c++ cast from int so ushort

Started by
7 comments, last by bubu LV 16 years, 8 months ago
the int will always be positive and within the range of possible values for a short. external library has poor design. int x = getWidth(); unsigned short xx = x; //how to cast this in c++
Advertisement
unsigned short xx = static_cast<unsigned short>(x);


Quote:Original post by ToohrVyk
EDIT: mine's formatted better [wink]


Not any more [razz].
unsigned short xx = static_cast<unsigned short>(x);


EDIT: mine's formatted better [wink]
unsigned short xx = *reinterpret_cast<unsigned short *>(&x);

!!!!!!!! :P
but the static cast will account for negative numbers, or big numbers, and the r_c won't. right?
The reinterpret_cast is bad for a lot of reasons. Number one of which is that it won't work properly in a number of situations. For example, using it on a big-endian machine will cause it to reinterpret the wrong set of bytes. There's no reason to get cute when doing a simple cast.
Quote:Original post by SiCrane
The reinterpret_cast is bad for a lot of reasons. Number one of which is that it won't work properly in a number of situations. For example, using it on a big-endian machine will cause it to reinterpret the wrong set of bytes. There's no reason to get cute when doing a simple cast.


I completely agree. I was indeed trying to be cute, and in no way meant it to be taken seriously.
Why are you copying it to an unsigned short? What do you gain? The fact that it is "always" positive and that it fits in a short are not really very good reasons.
John BoltonLocomotive Games (THQ)Current Project: Destroy All Humans (Wii). IN STORES NOW!
typedef unsigned short ushort;ushort xx = ushort(x);

This topic is closed to new replies.

Advertisement