Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

casting int to char using C++ style casting [duplicate]

In traditional C you can do:

int i = 48; char c = (char)i; //Now c holds the value of 48.  //(Of course if i > 255 then c will not hold the same value as i).   

Which of the c++ casting methods (static_cast, reinterpret_cast) is suited for getting this job done?

like image 962
Subway Avatar asked Jun 03 '13 14:06

Subway


People also ask

Can we type cast int to char in C?

We can convert an integer to the character by adding a '0' (zero) character. The char data type is represented as ascii values in c programming. Ascii values are integer values if we add the '0' then we get the ASCII of that integer digit that can be assigned to a char variable.

Can I cast int to char?

An integer can be converted into a character in Java using various methods. Some of these methods for converting int to char in Java are: using typecasting, using toString() method, using forDigit() method, and by adding '0'.

Can I use static_cast in C?

Static casts are only available in C++. Static casts can be used to convert one type into another, but should not be used for to cast away const-ness or to cast between non-pointer and pointer types.


1 Answers

You should use static_cast<char>(i) to cast the integer i to char.

reinterpret_cast should almost never be used, unless you want to cast one type into a fundamentally different type.

Also reinterpret_cast is machine dependent so safely using it requires complete understanding of the types as well as how the compiler implements the cast.

For more information about C++ casting see:

  • When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?
  • http://www.cplusplus.com/doc/tutorial/typecasting/.
like image 148
Felix Glas Avatar answered Oct 14 '22 12:10

Felix Glas