-
[C++] Decimal to BinarymyCode/GeneralKnowledge 2016. 8. 15. 11:26
10진수의 수를 2진수로 변환해보자!
가장 유명한 방법은 while 문을 이용해서 해당하는 십진수의 숫자를 2로 나눠가면서 나머지를 string에다가 붙여가는 방법이다.
#include <iostream> #include<string> std::string toBinary(int n) { std::string r; while(n!=0) {r=(n%2==0 ?"0":"1")+r; n/=2;} return r; } int main() { std::string i= toBinary(10); std::cout<<i; }
C++의 std::bitset을 이용한 방법도 있다.
bitset은 처음에 최대 비트이 크기를 정해놓고 사용해야하므로 substr으로 필요없는 앞의 0들을 잘라내는게 중요.
#include <iostream> #include <string> #include <bitset> #include <limits> int main() { while ( true ) { std::cout << "Enter a non-negative number (0-exit): "; unsigned long long x = 0; std::cin >> x; if ( !x ) break; std::string s = std::bitset<std::numeric_limits<unsigned long long>::digits>( x ).to_string(); std::string::size_type n = s.find( '1' ); std::cout << s.substr( n ) << std::endl; } }
참조 - http://stackoverflow.com/questions/22746429/c-decimal-to-binary-converting
'myCode > GeneralKnowledge' 카테고리의 다른 글
[C++] STL sort 튜토리얼 (0) 2016.08.15 KLDP 포스트 하나, 및 기초 함수 구현법 (strcpy, atoi) (0) 2016.07.27 [C++] 조합(Combination) 구하기 (0) 2016.06.06 Towers of Hanoi (0) 2016.04.24 Tales of Mintrupt - about int* and int[] (0) 2016.04.21