简体   繁体   中英

cast one element of char array to int

I have char array:

char c[10]="ff213";

and I need to cast one element of char to int. I tried this:

int i=atoi(c[2]);

But I get Runtime error. And this:

int i=(int)c[2];

But it returns 50 instead of 2. How can I do that?

Like so:

const int digit2 = c[2] - '0';

This works because C guarantees that the encodings for the decimal digits are in sequence and without any gaps.

This is not (as you can see) a "cast", it's just plain computation. If you cast the character, you get the encoding's representation as an integer, in your case 50 (hex 0x32) which is the ASCII (and UTF-8, and a bunch of other encodings) encoding of the digit 2.

The reason for the error you're getting is that atoi() expects a string (ie a char* to a null-terminated string).

Not only you're giving atoi() a char and not a pointer, the null-byte ( '\\0' ) only exists after the 5th char.

The easiest way of accomplishing what you're after is:

int i = c[2] - '0';

This way, the ascii code for '2' (50) is subtracted by the ascii code for '0' (48), and yield the correct answer for i .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM