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 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.)
See http://www.cplusplus.com/reference/clibrary/cstdlib/strtoul/ for docs.