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?
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.
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'.
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.
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:
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