[問題] bitwise compliment
開發平台(Platform): (Ex: VC++, GCC, Linux, ...)
linux
額外使用到的函數庫(Library Used): (Ex: OpenGL, ...)
無
問題(Question):
為何要加上副程式中的pbstr[SIZE]='\0'???
餵入的資料(Input):
分別輸入34,23,其中輸入23時已將副程式中的pbstr[SIZE]去掉
預期的正確結果(Expected Output):
34
00000000000000000000000000100010
11111111111111111111111111011101
錯誤結果(Wrong Output):
23
00000000000000000000000000010111昍昍昍昍昍昍
11111111111111111111111111101000昍昍昍昍昍昍
去掉副程式中的pbstr[SIZE]='\0'後
程式碼(Code):(請善用置底文網頁, 記得排版)
#include <stdio.h>
void itobstr(int n,char* pbstr);
int main(void)
{
int num;
char bstr[8*sizeof(int)+1];
printf("enter a integer:\n");
while(scanf("%d",&num)== 1)
{
itobstr(num,bstr);
printf("%s\n",bstr);
itobstr(~num,bstr);
printf("%s\n",bstr);
}
return 0;
}
void itobstr(int n,char* pbstr)
{
int size= 8*sizeof(int);
pbstr[size]='\0';
while(size> 0)
{
pbstr[size-1]=n&1?'1':'0';
n>>=1;
size--;
}
}
補充說明(Supplement):
函式最後一段的SIZE--
我一直搞不懂為何要做此動作??
我只知道不做這動作便不會轉成2進位碼....
請各位前輩指點迷津!!
謝謝
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 180.177.40.244
→
05/04 19:55, , 1F
05/04 19:55, 1F