Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C convert hex to decimal format

Tags:

c

decimal

hex

Compiling on linux using gcc.

I would like to convert this to hex. 10 which would be a. I have managed to do this will the code below.

unsigned int index = 10;
char index_buff[5] = {0};
sprintf(index_buff, "0x%x", index);
data_t.un32Index = port_buff;

However, the problem is that I need to assign it to a structure and the element I need to assign to is an unsigned int type.

This works however:

data_t.un32index = 0xa;

However, my sample code doesn't work as it thinks I am trying to convert from an string to a unsigned int.

I have tried this, but this also failed

data_t.un32index = (unsigned int) *index_buff;

Many thanks for any advice,

like image 539
ant2009 Avatar asked Nov 30 '22 07:11

ant2009


1 Answers

Huh? The decimal/hex doesn't matter if you have the value in a variable. Just do

data_t.un32index = index;

Decimal and hex are just notation when printing numbers so humans can read them.

For a C (or C++, or Java, or any of a number of languages where these types are "primitives" with semantics closely matching those of machine registers) integer variable, the value it holds can never be said to "be in hex".

The value is held in binary (in all typical modern electronic computers, which are digital and binary in nature) in the memory or register backing the variable, and you can then generate various string representations, which is when you need to pick a base to use.

like image 61
unwind Avatar answered Dec 05 '22 06:12

unwind