c++ 十六进制字符串转换二进制字符串, 二进制在转换十进制

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/max2009verygood/article/details/82775034

#include <stdio.h>;
#include <string.h>;
#include <stdlib.h>;

/*
*        10进制字符转成16进制字符
*/
int strDec2Hex(char* sDec, int iDecLen, char* sHex, int iHexLen)
{
	char sSrc[65];
	char sForamt[6];
	unsigned long ulSrc;
	memset(sSrc, 0, sizeof(sSrc));
	memcpy(sSrc, sDec, iDecLen);
	ulSrc = atol(sSrc);
	sprintf(sForamt, "%%0%dX", iHexLen);
	_snprintf(sHex, iHexLen, sForamt, ulSrc);
	return ulSrc;
}
/*
*        2进制字符转成16进制字符
*/
int strBin2Hex(char* sBin, int iBinLen, char* sHex, int iHexLen)
{
	char sSrc[65];
	char sForamt[6];
	unsigned long ulSrc;
	memset(sSrc, 0, sizeof(sSrc));
	memcpy(sSrc, sBin, iBinLen);
	*(sSrc + 0) == '1' ? ulSrc = 1 : ulSrc = 0;
	for (int i = 1; i < iBinLen; i++)
		*(sSrc + i) == '1' ? ulSrc = ulSrc * 2 + 1 : ulSrc = ulSrc * 2 + 0;
	sprintf(sForamt, "%%0%dX", iHexLen);
	_snprintf(sHex, iHexLen, sForamt, ulSrc);
	return ulSrc;
}

/*
*        16进制字符转成10进制字符
*/
int strHex2Dec(char* sHex, int iHexLen, char* sDec, int iDecLen)
{
	char sSrc[65];
	char sForamt[6];
	unsigned long ulSrc;
	memset(sSrc, 0, sizeof(sSrc));
	memcpy(sSrc, sHex, iHexLen);
	strupr(sSrc);
	*(sSrc + 0) < 'A' ? ulSrc = *(sSrc + 0) - 0x30 : ulSrc = *(sSrc + 0) - 0x41 + 0x0A;
	for (int i = 1; i < iHexLen; i++)
		*(sSrc + i) < 'A' ? ulSrc = ulSrc * 16 + *(sSrc + i) - 0x30 : ulSrc = ulSrc * 16 + *(sSrc + i) - 0x41 + 0x0A;
	sprintf(sForamt, "%%0%du", iDecLen);
	_snprintf(sDec, iDecLen, sForamt, ulSrc);
	return ulSrc;
}

/*
*        16进制字符转成2进制字符
*/
int strHex2Bin(const char* sHex, int iHexLen, char* sBin, int iBinLen)
{
	char sSrc[65];
	char sForamt[6];
	unsigned long ulSrc;
	memset(sSrc, 0, sizeof(sSrc));
	memcpy(sSrc, sHex, iHexLen);
	*(sSrc + 0) < 'A' ? ulSrc = *(sSrc + 0) - 0x30 : ulSrc = *(sSrc + 0) - 0x41 + 0x0A;
	for (int i = 1; i < iHexLen; i++)
		*(sSrc + i) < 'A' ? ulSrc = ulSrc * 16 + *(sSrc + i) - 0x30 : ulSrc = ulSrc * 16 + *(sSrc + i) - 0x41 + 0x0A;
	sprintf(sForamt, "%%0%dd", iBinLen);
	memset(sSrc, 0, sizeof(sSrc));
	ultoa(ulSrc, sSrc, 2);
	sprintf(sForamt, "%%0%ds", iBinLen);
	_snprintf(sBin, iBinLen, sForamt, sSrc);
	return ulSrc;
}

//十六进制转换二进制

void main()
{
	const char* sHex = "83";
	int iHexLen = 2;
	char* sBin = new char[9];
	memset(sBin, 0, 9);
	int iBinLen = 9;
	int iR = strHex2Bin(sHex, 2, sBin, 8);
	cout << iR << endl;
	cout << sBin << endl;
	string strBin(sBin);
	string strsBin = strBin.substr(1, 7);

	int ii = strtol(strsBin.c_str(), NULL, 2);

	printf("ii=%d\n", ii);

	system("pause");
}
string strBin(sBin);
	string strsBin = strBin.substr(1, 7);

	int ii = strtol(strsBin.c_str(), NULL, 2);

	printf("ii=%d\n", ii);

//二进制转换十进制

 

展开阅读全文

没有更多推荐了,返回首页