C++2015. 11. 17. 19:43

문제:

다음 text file (test.txt)의 16진수 수를 읽어 unsigned type 변수에 저장.

 

test.txt:

0x10

 

 

풀이:

아래 code (main.cpp)와 같이 hex를 이용하는 것이 핵심.

 

main.cpp:

#include <fstream>

#include <iostream>

 

using namespace std;

 

int main() {

  ifstream ifile("test.txt");

 

  unsigned a;

  ifile >> hex >> a;

 

  cout << "a = " << a << endl;

  return 0;

}

 

 

결과:

 

 

 

특이사항들:

  • Text file에서 0x를 빼고 10만 써도 같은 결과가 나온다. 즉, prefix인 0x는 선택사항.
  • 만약, hex를 빼고 ifile >> a;를 하면, a = 0이 나온다. 
    • 이건 0x0이 읽혀서 나온 것.
    • 만약, test.txt에 저장된 숫자가 0x10이 아니라 9x10 이라면, 9가 나옴. 
  • test.txt010으로 넣어도 결과는 16이 나온다. 즉, octal로  읽히고 hexa로 읽힌다.
  • File 뿐 아니라 다른 stream (e.g. stringstream)에도 응용 가능. 

'C++' 카테고리의 다른 글

C++ - 숫자를 binary (이진법) 형식으로 출력하기  (0) 2015.10.24
Posted by topazus
C++2015. 10. 24. 20:57

문제:

C++를 이용하여 숫자를 binary (이진법)으로 출력하라.

 

 

풀이:

다음과 같이 <bitset>을 이용하면 간단하다.

 

main.cpp

#include <bitset>

#include <iostream>

 

using namespace std;

 

int main() {

  unsigned int a = 1234;

  cout << bitset<32>(a) << endl;

  return 0;

}

 

 

결과:

 

 

 

참고:

16진법 (hexadecimal), 8진법 (octal)은 다음과 같이 하면 된다.

 

main.cpp:

#include <iostream>

 

using namespace std;

 

int main() {

  int a = 1234;

  cout << dec << a << endl;

  cout << hex << a << endl;

  cout << oct << a << endl;

  return 0;

}

 

 

결과:

 

'C++' 카테고리의 다른 글

C++ - File (stream)에서 16진수 값 읽기  (0) 2015.11.17
Posted by topazus