초보는슬프다 님이 쓰신 글 :
: 10진수를 2진수로 만들려하는데
: 도통 감을못잡겠네요
: 프로그램좀 알려주시면 고맙겠습니다 ㅠ.ㅠ
: 부탁드림다....
: ㅠ.ㅠ
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으로 변환합니다.
|