c/c++实现二进制/十进制/十六进制互转

10 篇文章 0 订阅

十进制转换N进制

  • 辗转相除法:
  • 常见的是转二进制和十六进制,且是以字符串的形式输出,

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

typedef unsigned char uint8_t;
typedef unsigned long uint64_t;


static int BinaryToInt(const char *bits, size_t nCnt)
{
	assert(nCnt <= sizeof(int));
	int ret = 0;
	for (size_t i = 0; i < nCnt; ++i)
	{
		ret += (bits[i] - '0') << (nCnt - i - 1);
	}
	return ret;
}

static std::string IntToBinary(int val, size_t nCnt)
{
	std::string ret(nCnt, '0');
	for (size_t i = 0; i < nCnt; ++i)
	{
		ret[nCnt - i - 1] = val % 2 + '0';
		val /= 2;
	}
	return ret;
}



//求数的二进制最高位的幂指数,即MSB
static size_t getMinPolynomialBits(uint64_t n) {
    size_t r = 0;
    while (n) {
	    n >>= 1;
    	r++;
    }
    return r;
}

//十进制转二进制字符串,Flag表示是否在前置位补0为标准形式
int dec2BinaryString(uint64_t inputDec, char* binary, int Flag) 
{
    size_t length = getMinPolynomialBits(inputDec) + 1; // 二进制表示的最少位数,如十进制15至少需要4位二进制位表示
	
    size_t padNum = (length%4 ? (4-length%4) : 0); // 高位补0数
	size_t resultLen = length + padNum ;
	int index = 0;
	int tmp = 0;

	char* result = (char*)malloc(sizeof(char) * ( resultLen + 1));
	memset(result, '0', sizeof(char) * (resultLen)); //初始化为0
	while (inputDec) {
		tmp = inputDec % 2; //除2取余
		index++;
		if (tmp==1) {
		//从低位往高位赋值
			result[resultLen - index] = '1';
		}
		else {
			result[resultLen - index] = '0';
		}
		inputDec >>= 1;
	}
	// 如果要输出为二进制的标准形式(4的倍数)字符串
	if (Flag) {
        //will to be fill zero in highest bit
        memcpy(binary, result, sizeof(char) * resultLen);
	}
	else {
		memcpy(binStream, result, sizeof(char) * length);
	}
    free(result);
    result = NULL;
    return 0;
}

/*
* dec2Binary - decimal number convert to binary string
* @inputDecValue[IN]: input dec value
* @pBinaryStream[OUT]: binary bit stream
* @length[IN]: if equal to 0, return The smallest number of bits converted from decimal to binary, else be fill zero in highest bit to length
*/
int dec2Binary(uint64_t inputDecValue, char* pBinaryStream, int length) {

    if(pBinaryStream==NULL){
        return -1;
    }
    int len  = strlen(pBinaryStream);
    //printf("Debug: %d\n", len);

    int minBits = getMinPolynomialBits(inputDecValue);
    uint64_t inputDecimal = inputDecValue;
    if (length <= minBits) {
        minBits = getMinPolynomialBits(inputDecimal);
    }

    int index = 0;
    char* result = (char*)malloc(sizeof(char) * (minBits + 1));
    //will to be fill zero in highest bit
    memset(result, '0', sizeof(char) * minBits);

    int remainder = 0;
    while (inputDecimal) {
        remainder = inputDecimal % 2;
        index++;
        if (remainder == 1) {
            result[minBits - index] = '1';
        }
        else {
            result[minBits - index] = '0';
        }
        inputDecimal >>= 1;
        if (minBits < index) {
            break;
        }
    }
    memcpy(pBinaryStream, result, sizeof(char) * minBits);
    free(result);
    result = NULL;
    return 0;
}

void Binary2Decimal(const char* inputBinary, uint32_t* decValue)
{
    if (inputBinary == NULL)
        return ;
    int lenBinBits  = strlen(inputBinary);
    uint32_t nDecimal = 0;

    for (size_t i = 0; i < lenBinBits; i++)
    {
        nDecimal = inputBinary[i] & 1; // '0' convert 0
        nDecimal <<= (lenBinBits - 1 - i);
        *decValue += nDecimal;
    }
    return ;
}

//十进制转十六进制字符串
//decimal number convert to hex string
//参数length表示存储十进制字符串的最大长度
int dec2HexStream(uint64_t inputValue, unsigned int length, char* resStream) {

	uint64_t inputDecimal = inputValue;
	char* result = ( char*)malloc(sizeof( char) * (length + 1));
	//will to be fill zero in highest bit
	memset(result, '0', sizeof( char) * length);
	
	int msbIdx = 0;
	int tmp = 0;
	while (inputDecimal) {
		tmp = inputDecimal % 16;
		msbIdx++;
		if (tmp <= 9) {
			result[length - msbIdx] = tmp + '0';
		}
		else {
			result[length - msbIdx] = tmp - 10 + 'A';
		}
		inputDecimal >>= 4;
	}
	result[length] = '\0';
	

	if (msbIdx <= length) {
		memcpy(resStream, result, sizeof(char) * length);
		free(result);
		return 0;
	}
	else {
		printf("\n input parameter length less more msbIdx's length, %d < %d \n", length, msbIdx);
		free(result);
		return -1;
	}
}

//二进制字符串转16进制数字符串
int bin2Hex(const char* inputBin, uint64_t& decValue, char* hexStr) {
	int inputLen = strlen(inputBin);
	if (inputBin == NULL || inputLen == 0) {
		return -1;
	}

	unsigned int n = (inputLen % 4 ? (4 - inputLen % 4):0); //16进制高位补0数
	unsigned int idx = (inputLen + n) / 4; // 16进制位数

	char* result = (char*)calloc(idx + 1, sizeof(char));

	char* msg = (char*)calloc(inputLen + n , sizeof(char));
	memset(msg, '0', sizeof(char)*n);
	memcpy(msg + sizeof(char) * n, inputBin, sizeof(char) * inputLen);
	
	uint64_t dec = 0;
	char tmp[4] = { '0' };
	for (int k = 0; k < idx; k ++) {
		memcpy(tmp, msg + k*4, 4);
		uint64_t res = Bin2Decimal(tmp, 4);
		
		if (res >= 0 && res <= 9) {
			result[k] = res + '0';
		}
		if (res > 9 && res <= 15) {
			result[k] = res  + ('A'- 10);
		}
		//uint64_t tmpSum = 1;
		//for (size_t i = 0; i < idx - 1 - k; i++) {
			//tmpSum *= 16;
		//}
		dec += res * pow(16, idx-1 - k);
	}
	
	memcpy(hexStr, result, idx);
	decValue = dec;
	free(msg);
	free(result);
	return 0;
}

//Hexadecimal to binary, default high-position zero, refer to padZerosFlag = true
int hex2DecNumBinStream(const char* pInputHex, char* pOutputBin, uint64_t & nDecimal) {
	if (pOutputBin == NULL || pInputHex == NULL){
		printf("input points parameters  is unvalid!\n");
		return -1;
	}
	nDecimal = 0;
	int length = strlen(pInputHex);

	char* pBinary = (char*)malloc(length * 4 + 1);
	memset(pBinary, 0x0, length * 4 + 1);

	for (unsigned int index = 0; index < length; ++index)
	{
		char curChar = pInputHex[index];
		unsigned int nData = 0;
		if (curChar >= '0' && curChar <= '9')
		{
			nData = curChar - '0';
		}
		else if (curChar >= 'a' && curChar <= 'f')
		{
			nData = curChar - 'a' + 10;
		}
		else if (curChar >= 'A' && curChar <= 'F')
		{
			nData = curChar - 'A' + 10;
		}
		else
		{
			printf("input hex string %dth char is unvalid!\n",index);
			free(pBinary);
			pBinary = NULL;
			return -2;
		}
		nDecimal = nDecimal * 16 + nData;
	}

	if (0 != dec2BinaryString(nDecimal, pBinary, 1)) {
		free(pBinary);
		pBinary = NULL;
		return -2;
	}

	if (pOutputBin) {
		memcpy(pOutputBin, pBinary, length * 4);
	}
	free(pBinary);
	pBinary = NULL;
	return 0;
}

c++ 实现


int main()
{
    uint8_t binResult[12] = {0};
    size_t length = getPolynomialBits(17 + 1) + 1; // 二进制表示的最少位数

    size_t normalLen = length + (4-length%4); // 二进制输出的标准形式

    dec2BinStream(17, binResult, 0);
 	for(int i = 0; i < length; i++){
	    printf("%d ",  binResult[i]);
	}   
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值