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* namecontains 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 achar*to anunsigned 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 ashort, and then throwing away the rest. This is absolutely not what you want.Instead use the
std::strtoulfunction, which parses a string and gives you back the equivalent number:(You still need to use a cast, because
strtoulreturns anunsigned long. This cast is between two different integer types, however, and so is valid. The worst that can happen is that the number insidenameis too big to fit into ashort–a situation that you can check for elsewhere.)