Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
371 views
in Technique[技术] by (71.8m points)

casting - typcast does not cast the whole string to int (in C)

I have a problem. Typecast works not like I want. So I have a variable called sz of type char array. This array contains 0x421. But I want this as an integrer, not as a string. So I tried typecasting like that:

char sz[16];
strcpy(sz, "x21x04");
printf("%d
", (int)*sz);

But this does only output 33 which is 0x21. But where is the 0x4 in front? My ltrace output:

strcpy(0x7ffdc6cf4b70, "!04")                                                    = 0x7ffdc6cf4b70
printf("%d
", 33)

Can someone help me?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

*sz is the same as sz[0], i.e. the first character of the string. In your case the first character has the numeric value 33 (aka hex 0x21). In other words, your code prints 33.

If you want to convert the first sizeof(int) characters to an integer, you should use bit shifting instead.

If sizeof(int) is 4 and you want little endian conversion, it would be something like:

int n = (sz[3] << 24) + (sz[2] << 16) + (sz[1] << 8) + sz[0];

note: depending on whether char is signed or unsigned, you may have to add a cast to unsigned before shifting.

note: Instead of + you can also use | (i.e. bitwise OR).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...