Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a hexadecimal value into a signed integer in PHP?

Tags:

php

hex

I am trying to convert a hex string into a signed integer.

I am able to easily transfer it into an unsigned value with hexdec() but this does not give a signed value.

Edit:

code in VB - the two "AA" hex values are representative.

Dim bs(2) As Byte
bs(1) = "AA"
bs(2) = "AA"
Dim s As Short
s = BitConverter.ToInt16(bs, 1)
like image 329
Graham Avatar asked Oct 26 '25 04:10

Graham


1 Answers

Check out this comment via php.net:

hexdec() returns unsigned integers. For example hexdec("FFFFFFFE") returns 4294967294, not -2. To convert to signed 32-bit integer you may do:

<?php
echo reset(unpack("l", pack("l", hexdec("FFFFFFFE"))));
?>
like image 135
hsz Avatar answered Oct 28 '25 17:10

hsz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!