關於char越界的簡單c

結論:

1. char 有符號範圍是-128~127;無符號範圍是0~255;

2. 在存儲媒介中,數字都是補碼形式儲存的(含字符常量);

3. 正數補碼爲本身二進制,負數補碼:絕對值->取反->+1;

4. 補碼的補碼爲源碼:原碼求補碼是取反加1,補碼求原碼還是是取反加1(符號位除外) !


例子:

root@ubuntu:/mnt/temp/test_8.31# gdb test<span style="white-space:pre">	</span><strong><span style="color:#ff0000;">//gdb調試</span></strong>
GNU gdb (Ubuntu 7.7.1-0ubuntu5~14.04.2) 7.7.1
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "i686-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from test...done.
(gdb) list<span style="white-space:pre">	</span><strong><span style="color:#ff0000;">//源碼</span></strong>
1	#include <stdio.h>
2	#include <stdlib.h>
3	
4	int main()
5	{
6		char a,b,c1,c2;
7		a = 197;
8		b = 198;
9	
10		printf("%c,%c\n",a,b);
(gdb) list
11		printf("%d,%d\n",a,b);
12		exit(EXIT_SUCCESS);
13	}
(gdb) break 10<span style="white-space:pre">	</span><span style="color:#ff0000;"><strong>//斷點1爲第10行</strong></span>
Breakpoint 1 at 0x8048460: file test.c, line 10.
(gdb) break 11<span style="white-space:pre">	</span><strong><span style="color:#ff0000;">//斷點2爲第11行</span></strong>
Breakpoint 2 at 0x804847e: file test.c, line 11.
(gdb) r<span style="white-space:pre">	</span>//運行
Starting program: /mnt/temp/test_8.31/test 

Breakpoint 1, main () at test.c:10
10		printf("%c,%c\n",a,b);
(gdb) cont<span style="white-space:pre">	</span><strong><span style="color:#ff0000;">//斷點1運行結果</span></strong><span style="white-space:pre">	</span>
Continuing.
�,

Breakpoint 2, main () at test.c:11
11		printf("%d,%d\n",a,b);
(gdb) cont<span style="white-space:pre">	</span><strong><span style="color:#ff0000;">//斷點2運行結果</span></strong>
Continuing.
-59,-58<span style="white-space:pre">	</span><span style="color:#ff0000;">//197 的補碼是11000101,最高位是1,所以是負數,剩1000101(補碼),求源碼爲111011,爲59,加符號位"1",就是-59</span>
[Inferior 1 (process 19127) exited normally]





發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章