C convert hex to decimal

Compiling on linux using gcc.

I would like to convert this to hex. 10, which would be a. I managed to do this will be 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 the structure and the element I need to assign is the unsigned int type.

However, this works:

 data_t.un32index = 0xa; 

However, my sample code does not work, as it thinks I'm trying to convert from string to unsigned int.

I tried this, but it also failed

 data_t.un32index = (unsigned int) *index_buff; 

Thanks so much for any advice,

+3
source share
3 answers

A? Decimal / hex does not matter if you have a value in a variable. Just do

 data_t.un32index = index; 

Decimal and hexadecimal values ​​are simply indications when printing numbers so people can read them.

For C (or C ++ or Java, or any of several languages ​​where these types are "primitives" with semantics similar to those of machine registers) an integer variable, the value that it has, can never be specified as "be in hexadecimal format.

The value is stored in binary format (in all typical modern electronic computers, which are digital and binary in nature) in memory or register that support the variable, and then you can generate various string representations that you need to choose the base to use.

+12
source

I agree with the previous answers, but I thought that I would use code that actually converts a hexadecimal string to an unsigned integer to show how this is done:

 #include <stdio.h> #include <stdlib.h> int main(void) { char *hex_value_string = "deadbeef"; unsigned int out; sscanf(hex_value_string, "%x", &out); printf("%o %o\n", out, 0xdeadbeef); printf("%x %x\n", out, 0xdeadbeef); return 0; } 

Gives this when executed:

 emil@lanfear /home/emil/dev $ ./hex 33653337357 33653337357 deadbeef deadbeef 
+7
source

However, my sample code does not work, as it thinks I'm trying to convert from string to unsigned int.

This is because when you write the following:

 data_t.un32index = index_buff; 

You have a type mismatch. You are trying to assign an index_buff character index_buff to unsigned int ie data_t.un32index .

You should be able to assign index , as suggested directly, to data_t.un32index .

+2
source

Source: https://habr.com/ru/post/918087/


All Articles