I am trying to communicate with my vehicles OBD port using LibSerial. When ever i send a command to the vehicle it echos back a hexadecimal value but LibSerial returns this hexadecimal value back to me as a string, i.e. "0x01A". How would i convert this hex string into a double so that I can process it using the appropriate formulas.

## All 9 Replies

there is no such thing as a double in hex. Use `hexdec` to convert to an integer then explicitly cast the return to a double.

``````\$someHEx = "0x01A";
\$someDouble = (double)hexdec(\$someHex);``````

ok well is there an equivalent c++ function or code segment to the php hexdec function you mentioned above

I just realized I was in the C++ forum, haha, oh well. Here's the C++ equivalent

In C++ you can use the following

``````#include <cstdio>
int main(int argc, char** argv)
{
char* somehex = "05a1";
unsigned long somelong = strtoul(somehex, 16);
printf("%d", somelong);
return 0;
}``````

The strtoul wants three arguments ;)

``````/// Returns true if it was a good number
bool cvtHex(int& n,const char* p)
{
if (!p) return 0.0;
return sscanf(p,"%x",&n) == 1;
}
/// For PHP expert\$ only
inline int hexdec(const char* p) {
return p?strtoul(p,0,16):0;
}``````

`strtoul(<string>, NULL, <base to convert, 16 for hex>);` Also, ArkM, strtoul returns an unsigned long, not an int. And in your first function why are you type coercing 0.0 (double) to bool?

yea I figured that a null went in the middle.

Thanks for all the help

`strtoul(<string>, NULL, <base to convert, 16 for hex>);` Also, ArkM, strtoul returns an unsigned long, not an int. And in your first function why are you type coercing 0.0 (double) to bool?

1. It's of no importance that strtoul returns unsigned long int, there is a legal conversion from this type to int. Probably, that microcontroller is not capable to send unsigned long (long) numbers ;)
2. Yes, `return 0.0` was in the 1st variant of this improvisation. Fortunately, there is a proper downgrade conversions chain in C++: double => int => bool ;)

1. It's of no importance that strtoul returns unsigned long int, there is a legal conversion from this type to int. Probably, that microcontroller is not capable to send unsigned long (long) numbers ;)
2. Yes, `return 0.0` was in the 1st variant of this improvisation. Fortunately, there is a proper downgrade conversions chain in C++: double => int => bool ;)

Yeah, I just don't particularly like implicit type conversion in strictly typed language so I try to avoid it.

Yeah, I just don't particularly like implicit type conversion in strictly typed language so I try to avoid it.

Well, I don't like them too (within the limits of common sense), but I hate explicit casts (especially in C style).
Now let's come back to PHP ;)..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.