UNIX Socket FAQ

A forum for questions and answers about network programming on Linux and all other Unix-like systems

You are not logged in.

  • Index
  • » C
  • » Hexstring(ASCII) to HEX conversion..

#1 2009-08-08 02:32 PM

rvan
Member
Registered: 2009-02-27
Posts: 13

Re: Hexstring(ASCII) to HEX conversion..

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


int hexstr2bin(const char *hex_input, char *buf_output, size_t len);
static int hex2byte(const char *hex);
static int hex2num(char c);

main()
{
	int len;
	char* buf;

	const char* hex ="abcd1234567890";

	buf = (char*)malloc(100);

	len = strlen(hex);

	hexstr2bin(hex,buf,len);

	printf("Values in hex %s",buf);
}


int hexstr2bin(const char *hex_input, char *buf_output, size_t len)
{
	size_t i;
	int a;
	const char *ipos = hex;
	char *opos = buf;
	char *prefix = "0x";

	for (i = 0; i < len; i++) {
		a = hex2byte(ipos);
		if (a < 0)
			return -1;
		*opos++ = *prefix;
		
			
		*opos++ = a;

		
		//*opos++ = ',';
		ipos += 2;
	}
	return 0;
}


static int hex2byte(const char *hex)
{
	int a, b;
	a = hex2num(*hex++);
	if (a < 0)
		return -1;
	b = hex2num(*hex++);
	if (b < 0)
		return -1;
	return (a << 4) | b;
}


static int hex2num(char c)
{
	if (c >= '0' && c <= '9')
		return c - '0';
	if (c >= 'a' && c <= 'f')
		return c - 'a' + 10;
	if (c >= 'A' && c <= 'F')
		return c - 'A' + 10;
	return -1;
}

Offline

#2 2009-08-08 03:42 PM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Hexstring(ASCII) to HEX conversion..

Offline

#3 2009-08-09 06:46 AM

rvan
Member
Registered: 2009-02-27
Posts: 13

Re: Hexstring(ASCII) to HEX conversion..

Hi,

I understand that to print the hex values in %s is not right.

But i have an array..  "30" which has a hexstring of this format. which occupies 2 bytes... and I am converting it to hex and putting it in one byte.


Again the result prefixed with "0x" 0x30, should be stored in a char* and pass it on to another module. How do I know that values got stored in this format 0x30  ?

If i am not supposed to use %s... and supposed to use only %x, %x also prints some junk values.

- Thanks

Offline

#4 2009-08-09 08:47 AM

i3839
Oddministrator
From: Amsterdam
Registered: 2003-06-07
Posts: 2,239

Re: Hexstring(ASCII) to HEX conversion..

You shouldn't prefix binary data with "0x". Just go through a loop and print
the hex values with "0x%.2X " for each byte.

Offline

  • Index
  • » C
  • » Hexstring(ASCII) to HEX conversion..

Board footer

Powered by FluxBB