개인 공부/C++
2진수 <-> 10진수 변환 코드, bitset
_h.j
2020. 9. 4. 13:29
728x90
1. 2진수 <-> 10진수 변환 코드
#include <bits/stdc++.h>
using namespace std;
int main(){
int a, b, res1 = 0, res2 = 0;
cin >> a>>b;//a : 10진수 , b : 2진수
//10진 to 2진
for(int i =1 ; a>=1 ; i*=10){
res1 = (a%2)*i + res1;
a/=2;
}
//2진 to 10진
for(int j =0 ; b>=1 ; j++){
res2 += (b%10) * pow(2,j) ;
b/=10;
}
cout<<res1<<"(2)"<<endl;
cout<<res2;
return 0;
}
2.bitset 사용하여 10진수 -> 2진수
- 헤더파일 : <bitset>
- 사용법 : bitset<출력길이>(변수 or 십진수)
#include <bits/stdc++.h>
#include <bitset>
using namespace std;
int main(){
int a;
cin >> a;
cout<<bitset<4>(a);
return 0;
}
결과 타입이 int는 아니다.
저장할 때 string으로
string s = bitset<8>(a).to_string();
3. bitset 사용법
- bitset 헤더파일에서 제공하는 STL(standart template libary)
- 고정된 크기의 N 비트 배열
사용법
헤더파일 | #include <bitset> |
선언 | bitset<할당할 비트 수> 변수명 |
[n] | n + 1 번째(인덱스 n)비트가 1인지 0인지 검사 |
.test(n) | n + 1 번째(인덱스 n)비트가 1인지 0인지 검사 |
.all() | 모든 비트(all)가 1이면 1(true) 그렇지 않으면 0(false)을 반환 |
.any() | bitset 중 하나라도(any) 1이면 1(true)을 반환 한 개라도 1이 없다면, 즉 모두 0일 때 0(false)을 반환 |
.none() | bitset 중 1이 하나도 없다면(none), 즉 모두 0이면 1(true)을 반환 |
.count() | bitset 중에서 1인 비트의 개수를 반환 |
.size() | bitset의 크기를 구한다 |
.set() | 전체 비트를 1로 셋팅 |
.set(n, true/false) | n + 1번째(인덱스 n)비트를 1(true)또는 0(false)으로 셋팅 |
.reset() | 전체 비트를 0으로 리셋 |
.flip | 전체 비트를 토글. 0은 1로, 1은 0으로 |
.flip(n) | n + 1 번째(인덱스 n)비트를 토글. 0은 1로, 1은 0으로 |
.to_string() | 전체 비트를 string화 시킨다 |
.to_ulong() / .to_ullong() | 전체 비트를 unsigned long / unsigned long long의 값으로 바꿔준다 |
operator&= operator|= operator^= operator~ |
AND, OR, XOR and NOT 비트 연산을 수행 |
operator<<= operator>>= operator<< operator>> |
left shift연산과 right shift 연산을 수행 |
참고 사이트
728x90