티스토리 뷰

IT/C, C++

[C/C++] 2진수를 10진수 및 HEX 값으로 변환하기

주인장 진빼이

설명

유니코드를 보다가 다른 블로그에서 유니코드 설명한다면서 비트만 나열한 경우가 많았다.

또 운영체제에 기본적으로 포함된 계산기를 사용해 보면 여러개의 비트 값을 받아 한번에 10진수로 보는 건 힘들다.

(아주 긴 비트도 하나씩 밖에 안되더라)

 

그래서 나열된 비트값들이이 무엇을 의미하는지 10진수와 HEX값을 보기 위해 직접 만들었다.

처음엔 대충 만들까 생각해봤는데 여러개의 비트를 모두 읽어야할 필요가 있어보였다. 그래서 기능을 추가했다.

여담으로 기본 macOS 계산기보다 윈도우가 더 좋다.

 

 

프로그램은 복잡하지 않고 심플하다.

C++에서 split이 기본적으로 지원되지 않아서 조금 불편했지만 만드는건 어렵지 않았다.

아직은 콘솔버전만 존재한다.

 

스케치

#include <iostream>


using namespace std;
int main()
{
	char text[8+1];
	scanf("%s", text);

	cout << "입력한 데이터: " << text << "\n";

	unsigned char res = 0;
	for (int i=0; i<8; ++i)
	{
		if (text[i] >= '0')
			text[i] = text[i] - '0';

		if (text[i] == 0)
			continue;
		res |= text[i] << (7-i);
	}

	printf("%d (%#x)\n", res, res);
	return 0;
}

 

동적할당 응용


#include <iostream>
#include <cctype>

using namespace std;
int main()
{
	string binary_text;
	getline(cin, binary_text, '\n');

	cout << "입력한 데이터: " << binary_text << "\n";

	unsigned char res = 0;
	int bit_length = binary_text.length();
	int cnt = 0;
	for (int i=0; i<bit_length; ++i)
	{
		if (isdigit(binary_text[i]))
		{
			binary_text[i] -= '0';
			if (binary_text[i] != 0)
			{
				binary_text[i] = 1;
			}
			else
			{
				binary_text[i] = 0;
				continue;
			}
		}
		else
		{
			continue;
		}
		res |= binary_text[i] << (bit_length-i-1);
	}

	printf(">> %d (%#X)\n", res, res);
	return 0;
}

 

split을 이용한 여러개의 이진수 계산하기

#include <iostream>
#include <cctype>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

vector<string> split(string &str, char delim)
{
	vector<string> list;
	stringstream ss(str);
	string item;
	while(getline(ss, item, delim))
	{
		list.push_back(item);
	}
	return list;
}

int BinStrToHex(string binStr)
{
	unsigned char res = 0;
	int bit_length = binStr.length();
	for (int i=0; i<bit_length; ++i)
	{
		if (isdigit(binStr[i]))
		{
			binStr[i] -= '0';
			if (binStr[i] != 0)
			{
				binStr[i] = 1;
			}
			else
			{
				binStr[i] = 0;
				continue;
			}
		}
		else
		{
			continue;
		}
		res |= binStr[i] << (bit_length-i-1);
	}
	return res;
}

int main()
{
	string binary_text;
	getline(cin, binary_text, '\n');

	cout << "입력한 데이터: " << binary_text << "\n";

	vector<string> list = split(binary_text, ' ');

	vector<int> resList;
	int res = 0;
	int idx = 0;
	while (idx < list.size())
	{
		res = BinStrToHex(list.at(idx));
		resList.push_back(res);
		idx++;
	}

	for(int i=0; i<list.size(); ++i)
	{
		printf("%-10s", list.at(i).c_str());
	}
	cout << "\n";
	char s[32];
	for(int i=0; i<resList.size(); ++i)
	{
		sprintf(s, "%d(%#X)", resList.at(i),resList.at(i));
		printf("%-10s", s);
	}
	return 0;
}

 

결과값은 다음과 같다.

11101010 1001010 10001010             
입력한 데이터: 11101010 1001010 10001010
11101010  1001010   10001010  
234(0XEA) 74(0X4A)  138(0X8A) 

 

 

Visual Studio Code에서 작업했다.

온라인 IDE를 이용하면 쉽게 컴파일이 가능하다.

 

Windows OS Visual Studio에서 컴파일 한다면 safe 관련 이슈 에러가 발생한다.

댓글
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함