기본 콘텐츠로 건너뛰기

[C/C++[ shift 연산 음수로 이용하기

x = k >> -e // 이건 뭐 어쩌자는 건지?

c++ 소스 중에  오늘 위와 같은 형식의 shift 연산을 보고 결과가 궁금해서 테스트를 해봤다.
결론은 shift 연산자 우측에 음수가 오면 무조건 0
즉 -e 이렇게 쓴것은 e 의 값이 음수라는 이야기 이다.

#include "stdafx.h"

template<typename T>
void test_minus_shift(T value)
{
//T value = 1;
T nShfitLeft = value << 1;
T nShfitLeftMinus = value << -1;
T nShfitRight = value >> 1;
T nShfitRightMinus = value >> -1;
}

int _tmain(int argc, _TCHAR* argv[])
{
test_minus_shift<int>(1); // nShfitLeft=2, nShfitLeftMinus=-21474836, nShfitRight=0, nShfitRightMinus=0
test_minus_shift<int>(8); // nShfitLeft=16, nShfitLeftMinus=0, nShfitRight=4, nShfitRightMinus=0
test_minus_shift<int>(0xfc31); // nShfitLeft=129122, nShfitLeftMinus=-21474836, nShfitRight=32280, nShfitRightMinus=0

test_minus_shift<unsigned>(1); // nShfitLeft=2, nShfitLeftMinus=21474836, nShfitRight=0, nShfitRightMinus=0
test_minus_shift<unsigned>(8); // nShfitLeft=16, nShfitLeftMinus=0, nShfitRight=4, nShfitRightMinus=0
test_minus_shift<unsigned>(0xfc31); // nShfitLeft=129122, nShfitLeftMinus=21474836, nShfitRight=32280, nShfitRightMinus=0
return 0;
}

댓글

  1. 예전 embedded 시스템에서 사용하는 gcc 에서는 음수 시프트가 있습니다...

    그렇게만 아시면 나중에 뭐지.. 하실꺼에요 ㅎㅎ

    답글삭제
    답글
    1. 답글이 늦었지만, 그런것도 있군요... 좀 더 찾아봐야겠어요... 감사

      삭제

댓글 쓰기