Home > Blockchain >  c casting int to char with static_cast returns weird char
c casting int to char with static_cast returns weird char

Time:09-29

When I tried to cast a char to int using static_cast<char>(i) just like here 's top answers

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

//file name :main.cpp
#include <iostream>
int main()
{
    char char0 = 'h';
    int num = 1;
    char char1 = static_cast<char>(num);
    std::string combined = std::string()   char0   char1;
    printf("%s \n", combined.c_str());
    return 0;
}

it will only prints out "h" instead of "h1" for some reason, it's not because char1 is null because when I debugged it using gdb

g   -g main.cpp -o main
gdb main
break main.cpp:10
run
info locals

It says that

char0 = 104 'h'
num = 1
char1 = 1 '\001'
combined = "h\001"

combined 's value is "h\001" why is this happening?

CodePudding user response:

Things might become clearer to you if you take a look at an ASCII chart. A char with a byte value of decimal 1 corresponds to a special character "Start of Header" not a literal '1'. Try using num = 49, you should see the result of "h1".

So, the integer num has a byte value of b00000001, but a cast to char doesn't change that byte value, it just changes the way that value is interpreted. That's why a cast of int 1 to char isn't '1'.

You can see this in your debugger. Note the 104 'h'. 1 '\001' is how the debugger is presenting the special Start of Header character, like you'll see newline as '\n'.

  • Related