views:

2995

answers:

3

Hello,

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,

+7  A: 

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 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 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.

unwind
+1  A: 

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

This is because when you write the following:

data_t.un32index = index_buff;

you do have a type mismatch. You are trying to assign a character array index_buff to an unsigned int i.e. data_t.un32index.

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

dirkgently
+1  A: 

I agree with the previous answers, but I thought I'd share code that actually converts a hex string to an unsigned integer just to show how it's 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
Emil H