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
@ shiracamus's code is good.
Recommended Posts