Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert char* to unsigned short in C++

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.

like image 362
Elpezmuerto Avatar asked Jun 23 '10 15:06

Elpezmuerto


1 Answers

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.)

like image 174
JSBձոգչ Avatar answered Oct 01 '22 14:10

JSBձոգչ