I have a char* name
which is a string representation of the short I want, such as "15" and need to output this as unsigned short unitId
to a binary file. This cast must also be cross-platform compatible.
Is this the correct cast: unitId = unsigned short(temp);
Please note that I am at an beginner level in understanding binary.
I assume that your char* name
contains a string representation of the short that you want, i.e. "15"
.
Do not cast a char*
directly to a non-pointer type. Casts in C don't actually change the data at all (with a few exceptions)--they just inform the compiler that you want to treat one type into another type. If you cast a char*
to an unsigned short
, you'll be taking the value of the pointer (which has nothing to do with the contents), chopping off everything that doesn't fit into a short
, and then throwing away the rest. This is absolutely not what you want.
Instead use the std::strtoul
function, which parses a string and gives you back the equivalent number:
unsigned short number = (unsigned short) strtoul(name, NULL, 0);
(You still need to use a cast, because strtoul
returns an unsigned long
. This cast is between two different integer types, however, and so is valid. The worst that can happen is that the number inside name
is too big to fit into a short
--a situation that you can check for elsewhere.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With