bitset 으로 int 를 이진수로 표현하기
#include <bitset>
#include <iostream>
using namespace std;
int dd=3;
cout << "dd as binary short : " << bitset<numeric_limits<unsigned short>::digits>( dd ) << endl;
or
cout << "3 as binary short : " << bitset<numeric_limits<unsigned short>::digits>( 3 ) << endl;
http://www.borlandforum.com/impboard/impboard.dll?action=read&db=cpp_qna&no=563
10진수를 진법을 변환한다고 한다면 문자열로 변환한다는 거겠죠?
방법 1)
stdlib.h 에 있는
itoa(), ltoa(), ultoa() 함수를 쓰면 (Windows에만 있습니다. ANSI C 호환 안됩니다.)
int, long, unsigned long 형을 2~36진법(숫자 10 + 영문자 26)까지 선택하여
char* 형으로 변환할 수 있습니다.
itoa의 원형은 다음과 같습니다.
char *itoa(int value, char *string, int radix);
예제는 다음과 같습니다.
int main()
{
int number = 123;
char string[25];
itoa(number, string, 2);
printf("integer = %d string = %s\n", number, string);
return 0;
}
방법2)
2진법만으로의 변환이라면,
ANSI C++ 라이브러리의 bitset.h에 있는 bitset 클래스를 사용하면 됩니다.
10진수 -> 2진수, 2진수 -> 10진수로의 변환도 쉽게 할 수 있습니다.
물론 속도는 itoa()보다 빠릅니다.
예제는 다음과 같습니다.
int main() {
const bitset<12> mask(2730ul);
cout << "mask = " << mask << endl;
bitset<12> x;
cout << "Enter a 12-bit bitset in binary: " << flush;
if (cin >> x) {
cout << "x = " << x << endl;
cout << "As ulong: " << x.to_ulong() << endl;
cout << "And with mask: " << (x & mask) << endl;
cout << "Or with mask: " << (x | mask) << endl;
}
return 0;
}
출력은 다음과 같습니다.
mask = 101010101010
Enter a 12-bit bitset in binary: 111000111000
x = 111000111000
As ulong: 3640
And with mask: 101000101000
Or with mask: 111010111010
참고) 정수를 16진수로 변환할 때는 VCL의 IntToHex()도 많이 사용합니다.
단 이 경우는 AnsiString으로 변환합니다.
'STLTemplate > STL & EffectiveSTL' 카테고리의 다른 글
문자열과 integer,float 사이의 변환 (atoi, stringstream) (0) | 2012.11.01 |
---|---|
string 대소문자 변환 (0) | 2012.11.01 |
STL 무한대, numeric_limits::infinity (0) | 2012.11.01 |
lower_bound,upper_bound 예제소스 (0) | 2012.11.01 |
반복자 어댑터(Iterator Adaptors) – inserter(), back_inserter(), front_inserter() (0) | 2012.11.01 |