C 에서 overflow 된 연산 결과가 이상해요...
글쓴이: 익명 사용자 / 작성시간: 목, 2002/01/24 - 12:21오후
unix상에서 아래처럼 실행시켰는데요...
#include
int main() {
short s;
s=100000;
/* s=0x186A0; */
printf("s is [%d]\n",s);
return 0;
}
실제실행결과 -31702
저의예상결과 -7960
제생각에는 short가 2바이트니깐
100,000에 해당하는 0x186A0 이
앞에 1이 잘리고 0x86A0로 저장되는것같은데
음수이므로 2의보수로 읽으면 -7960 이 나와야하는데
실제로는 -31702가 나오네요.
문제가 뭔지, 확실히 아시는분 답변주심은 감사하겠습니다.
Forums:
Re: C 에서 overflow 된 연산 결과가 이상해요...
seeker wrote..
unix상에서 아래처럼 실행시켰는데요...
#include <stdio.h>
int main() {
short s;
s=100000;
/* s=0x186A0; */
printf("s is [%d]\n",s);
return 0;
}
실제실행결과 -31702
저의예상결과 -7960
제생각에는 short가 2바이트니깐
100,000에 해당하는 0x186A0 이
앞에 1이 잘리고 0x86A0로 저장되는것같은데
음수이므로 2의보수로 읽으면 -7960 이 나와야하는데
실제로는 -31702가 나오네요.
문제가 뭔지, 확실히 아시는분 답변주심은 감사하겠습니다.
0x86A0을 2진수로 바꾸면 1000011010100000 인데.
최상위비트가 1이므로 음수입니다..
따라서 님 말슴대로 보수를 취하면 111100101011111이 되고..
이걸 10진수로 바꿔보면 31071가 나옵니다..
+1시킨후 -부호를 붙여주면 음수가 되는거죠..
Re: C 에서 overflow 된 연산 결과가 이상해요...
안녕하세요 ~ 결과는 -31072인 것 같습니다.
뭐 별로 재미도 없는 일인데 그냥 계산기로 계산해봤습니다.
말씀대로 앞에 1이 잘려나가죠.
그런데 그 뒤의 값을 잘못 생각하고 계신 것을 보면 2의 보수를 잘못 이
해하고 계신가 아닌가 생각합니다. ^^;
다음은 잘리고 남은 값입니다.
1000011010100000
그리고 그걸 2의 보수 취해주면 양수가 나오는데 부호만 다를 뿐 그 크기
는 같죠.
1000011010011111
-1을 해줍니다.
0111100101100000
31072죠. 그러므로 -31072가 맞는 것 같습니다. ^^;
그럼 즐거운 하루 되시기 바랍니다. ~
댓글 달기