Language/C
[따배씨] 15.6 비트단위 쉬프트 연산자
migrationArc
2021. 7. 23. 18:58
따배씨 - 따라하며 배우는 C언어
15강 비트 다루기
15.6 비트단위 쉬프트 Shift 연산자
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
void int_binary(const int num);
int main()
{
/*
Bitwise shift operators
- Left shift
number << n : multiply number by 2^n
- Right shift
number >> n : divede by 2^n (for non-negative numbers)
*/
// 8 bit integer cases
//
printf("%hhd\n", 1 << 3);
// 00000001 -> 00000001??? -> 00001000
// 8
printf("%hhd\n", 8 >> 1);
// 00001000 -> ?00001000 -> 00000100
// 4
printf("%hhd\n", -119 >> 3);
// 10001001 -> ???10001001 -> 11110001
// -15
printf("%hhd\n", -119 << 4);
// 10001001 -> 10001001???? -> 10010000
// -112
// unsigned
printf("%hhd\n", 137 >> 3);
// 10001001 -> ???10001001 -> 00010001
// 17
printf("%hhd\n", 137 << 4);
// 10001001 -> 10001001???? -> 10010000
// -112
// singed 인 경우 right shift 의 경우 기계마다 다르지만, 주로 1로 채우게 됨
int a = 1;
a <<= 3;
a >>= 2;
printf("Unsigned int %u\n", 0xffffffff);
// Unsigned int 4294967295
printf("Signed int %d\n", 0xffffffff);
// Signed int -1
int_binary(0xffffffff);
// Decimal -1 == Bianry 11111111111111111111111111111111
printf("Right shift by 3\n");
// Right shift by 3
int_binary((signed)0xffffffff >> 3);
// Decimal -1 == Bianry 11111111111111111111111111111111
int_binary((unsigned)0xffffffff >> 3);
// Decimal -1 == Bianry 11111111111111111111111111111111
printf("\nUnsigned int %u\n", 0x00ffffff);
// Unsigned int 16777215
int_binary(0x00ffffff);
// Decimal 16777215 == Bianry 00000000111111111111111111111111
printf("Right shift by 3\n");
// Right shift by 3
int_binary((signed)0x00ffffff >> 3);
// Decimal 2097151 == Bianry 00000000000111111111111111111111
int_binary((unsigned)0x00ffffff >> 3);
// Decimal 2097151 == Bianry 00000000000111111111111111111111
return 0;
}
void int_binary(const int num)
{
printf("Decimal %3d \t== Bianry ", num);
const size_t bits = sizeof(num) * 8;
for (size_t i = 0; i < bits; i++)
{
const int mask = 1 << (bits - 1 - i);
// bit 연산자를 이용하여 mask 를 만듬, 더 효율적
if ((num & mask) == mask)
printf("%d", 1);
else
printf("%d", 0);
}
printf("\n");
}
이 글의 모든 사진과 내용의 출처는 홍정모 교수님께 있음을 알려드립니다.
http://blog.naver.com/atelierjpro
실리콘 밸리의 프로그래머 : 네이버 블로그
안녕하세요! 홍정모 블로그에 오신 것을 환영합니다. 주로 프로그래밍 관련 메모 용도로 사용합니다. 강의 수강하시는 분들은 홍정모 연구소 카페로 오세요.
blog.naver.com
http://www.inflearn.com/course/following-c
홍정모의 따라하며 배우는 C언어 - 인프런 | 강의
'따배씨++'의 성원에 힘입어 새롭게 개발된 C 언어로 시작하는 프로그래밍 입문 강의입니다. '따배씨'와 함께 프로그래밍 인생을 업그레이드 해보세요., 따라하며 배우는 C언어 '따배씨++'의 성원
www.inflearn.com