Skip to content

Instantly share code, notes, and snippets.

@DonghoonPark12
Last active April 23, 2019 01:35
Show Gist options
  • Save DonghoonPark12/bcbe6731051b3924ed6264bab5cea6bf to your computer and use it in GitHub Desktop.
Save DonghoonPark12/bcbe6731051b3924ed6264bab5cea6bf to your computer and use it in GitHub Desktop.
/*
비트 이동 연산을 이용하여 문자 4개를 받아서 하나의 unsigned int형의 변수 안에 저장하는 프로그램을 작성하라.
첫 번째 문자는 비트 0부터 비트 7까지에 저장되고, 두 번째 문자는 비트 8부터 비트 15까지,
세 번째 문자는 비트 16에서 비트 23까지, 네 번째 문자는 비트 24부터 비트 31까지에 저장된다.
결과로 생성되는 정수값은 16진수로 출력하도록 한다. 비트 이동 연산과 비트 OR 연산을 사용하라.
*/
#include <iostream>
int main() {
char a, b, c, d;
unsigned int res = 0x00000000;//32bit
printf("첫번째 문자: ");
scanf(" %c", &a);//8bit
res = res | a;
printf("두번째 문자: ");
scanf(" %c", &b);
res = res | b << 8;
printf("세번째 문자: ");
scanf(" %c", &c);
res = res | c << 16;
printf("네번째 문자: ");
scanf(" %c", &d);
res = res | d << 24;
printf("결과 값: %x", res);
return 0;
}
@DonghoonPark12
Copy link
Author

DonghoonPark12 commented Apr 23, 2019

char로 문자를 받아서 shift를 하면 저장할 bit 공간이 없을 수 있어 에러가 날 줄 알았는데 그러지 않았다.
16진수의 출력은 %x 이다.
0x를 붙여서 출력하고 싶다면 %#x 이다.
0x를 붙여서 8자리로 출력하고 싶다면 %#08x이다.(이때 앞에 0이 있다면 무시되고 0x가 붙는다. e.g. 00367555 -> 0x367555)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment