[GO] C> Convert decimal to hexadecimal> Do not use sprintf ()

Consider how to convert from decimal number to hexadecimal number without using sprintf () in C language. There may be an option not to use sprintf () when the memory constraint is strict in the microcomputer.

code v0.1

http://ideone.com/GsX2DR

#include <stdio.h>
#include <stdbool.h>

bool toHex1(int val, char *dstPtr){
	if (dstPtr == NULL) {
		return false;
	}
	sprintf(dstPtr, "%X", val);
	return true;
}
bool toHex2(int val, char *dstPtr) {
	if (dstPtr == NULL) {
		return false;
	}
	
	char wrkstr[5];
	static const int maxbit = 16;
	int wrkval = val;
	int bit = 0;
	while(bit <= maxbit) {
		wrkval = (val >> bit & 0xF);
		if (wrkval == 0) {
			break;
		}
		if (wrkval < 10) {
			wrkstr[bit/4] = '0' + wrkval;
		} else {
			wrkstr[bit/4] = 'A' + (wrkval - 10);
		}
//		printf("%d", wrkval);
		bit += 4;
	}
	
	int idx = bit / 4 - 1;
	while(idx >= 0) {
		dstPtr[idx] = wrkstr[bit / 4 - idx - 1];
		idx--;	
	}

	return true;		
}

int main(void) {
	int val=65534;
	char res[20];
	
	if(toHex1(val, res)) {
		printf("%d %s\n", val, res);
	}
	if(toHex2(val, res)) {
		printf("%d %s\n", val, res);
	}
	
	return 0;
}

result


65534 FFFE
65534 FFFE

It has become something complicated again.

TODO: I made a mistake when the value is 0. http://ideone.com/94tjai

code v0.2 (improved version)

@ shiracamus's code is good.

Recommended Posts

C> Convert decimal to hexadecimal> Do not use sprintf ()
[Python] Convert decimal numbers to binary numbers, octal numbers, and hexadecimal numbers
Convert hexadecimal string to binary
Convert IP address to decimal
Convert decimal numbers to n-ary numbers [python]
How to use Google Test in C
Use pandas to convert grid data to row-holding (?) Data
Not much mention of how to use Pickle
Python> tuple> (3., 1., 4.) to 3.00000, 1.00000, 4.00000 (decimal point to 5 digits)> Use .join