Jump to content

Unsigned hex numbers with a negative value.


adammw

Recommended Posts

Hi.

I've recently been having trouble with my latest project, where I'm trying to get information from the game, OpenTTD. So far so good, except I can't figure out how to handle negative numbers. All numbers are sent as little-endian in hex, so it makes it really confusing.

So far I have,

function unle($str) {
// This function converts a little endian string into a decimal number
for ($i = 0; $i < strlen($str); $i++) {
	$hex[$i] = str_pad(dechex(ord($str[$i])),2,'0',STR_PAD_LEFT);
}
$hex = array_reverse($hex);
$val = hexdec(implode($hex));
return $val;
}

which works perfectly for normal positive values but when it hits a negative value (such as 1ef6ffffffffffff ) it goes crazy and comes back with a float(1.84467440737E+19) - according to the game I'm pretty sure it should be -2530. I've tried converting to binary and back and using the "complement" but I don't think i was doing that right and it didn't work.

 

Thanks.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.