Convert char array to int to Hex string

I am using the following code to parse GPS data:

char gpsLat[11];
          strncpy(gpsLat, gpsResponse + 18, 10);
          gpsLat[10] = '\0';

This outputs:
2551.36774

I must now multiply this by 100000, so (2551.36774 * 100000 = 255136774 )

Then I must convert 255136774 to a Hex string, which is: 0F351406.

I have looked at a lot of char to various conversions, but cannot find a solution that works.

Why?

The processor works only in binary. It knows no difference between HEX and DEC. Those representations are for humans.

To make it human readable hex just print in hex
Serial.println(255136774, HEX);

i agree with gF above ^^, why? but if you do have some reason....

one potential problem with his solution is, it wont print leading 0's (neither will BIN serial print).

here are a couple helper functions I use to make the prints more readable (these are 1 byte at a time, modify as needed)

void printBinary(uint8_t binNum)
{
    Serial << "0b";
    for(int8_t i=7; i >=0;i--)
          Serial.print(bitRead(binNum, i));
}

void printHex(uint8_t hexNum)
{
    Serial << "0x";
    if(hexNum <=15)
       Serial << "0";
    Serial.print(hexNum, HEX);
}

if you actually need to but that number into a string, I use itoa():

char cBuff[numDigits]={ };
itoa(myInt , cBuff , 10);        

that will put the digits of myInt into cBuff. do what you like with it from there.

the last argument is the base, I've only every use it as 10, but I think you should be able to set it to 16 and get the hex digits in the string.

The string is sent via Sigfox

(untested)

char gpsLat[10];
char latHex[9];
          strncpy(gpsLat, gpsResponse + 18, 4);
          strncpy(&gpsLat[4], gpsResponse + 23, 5);
          gpsLat[9] = '\0';
          sprintf(latHex, "%08X", atol(gpsLat));

With an actual Lat of: 2551.37308
Running the above code, I get: 0000161C
It should be: 0F35161C

My bad. Try

"%08lX"

Note: lower-case l, upper-case X

Here's a guide to using sprintf()

1.

Post the whole codes so that we can see what type of variable (float or array) holds the value 2551.36774.

2.

If you do the multiplication using paper-pencil, you will get 255136774. If MCU of the UNO Board is asked to the multiplication, it will never give you 255136774 as arithmetic on float numbers are not exact. For example:

  float y1 = 2551.36774;
  y1 = 2551.37308*100000.0;  //expecting: 255136774
  unsigned long y2 = (unsigned long)y1;
  Serial.println(y2, DEC); //shows: 255137312
  Serial.println(y2, HEX); //shows:F351620

Many thanks - works perfectly

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.