앱 개발/Java

자바 비트 연산, 쉬프트 연산자

맨땅 2021. 12. 22. 09:13
반응형

High byte, low byte 추출

 

실무 중 열받아서 정리하게 되었습니다

다른 분들도 보고 도움이 되셨으면 좋겠습니다

 

[MainActivity.Java]

byte aa = (byte)0x31

Log.d("Simulators", "high byte는 1 " + Integer.toHexString(aa & 0xF0)); //hihg byte만 추출(0x30)
Log.d("Simulators", "high byte는 2 " + Integer.toHexString(aa & 0xf0)); //위와 동일(소문자 써도 됌)

Log.d("Simulators", "low byte는 " + Integer.toHexString(aa & 0x0f)); //low byte만 추출(0x01)

Log.d("Simulators", "shift 연산자는 " + Integer.toHexString(aa << 8)); //8bit 앞으로 민거(0x3100)

위는 안드로이드 스튜디오 oncreate에 작성했습니다.

 

 

Integer.toHexString

를 사용한 이유는 Integer.toHexString 없이 찍어보면 48 즉 10진수값이 나오기 때문에 Hex값으로 보기 위해서 사용했습니다

 

만약 aa<<24 한 31000000에 aa를 더해 31000031을 표현하고 싶다면

 

byte aa = (byte)0x31;
int hh;
int pp;

        hh = aa<<24;
        Log.d("Simulators", "hh는 " + Integer.toHexString(hh)); //31000000
        pp = (hh+aa);
        Log.d("Simulators", "계산 결과(pp)는 " + Integer.toHexString(pp)); //31000031

 

이렇게 해주시면 됩니다

반응형