Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

c C++ convert hex to ascii (See related posts)

// Presented with hex such as 0x12345abc perhaps there is a spot in there
// which represents an ascii char - such as 53 would be 'S'
// Common when dealing with hardware-related data structures and wire
// protocols

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

/*
*	To convert 53 to the character 'S':
*	char returnVal = hexToString('5', '3');
*/
char hexToAscii(char first, char second)
{
	char hex[5], *stop;
	hex[0] = '0';
	hex[1] = 'x';
	hex[2] = first;
	hex[3] = second;
	hex[4] = 0;
	return strtol(hex, &stop, 16);
}
int main(int argc, char* argv[])
{
	printf("%c\n", hexToAscii('5', '3'));
}

produces this output:
S

You need to create an account or log in to post comments to this site.


Click here to browse all 4858 code snippets

Related Posts