'hex'에 해당되는 글 1건

  1. 2015.11.17 C++ - File (stream)에서 16진수 값 읽기
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