How to calculate 2's complement of a HEX value ?

I need to calculate the two’s complement of a HEX value, but am struggling using dechex, hexbin etc. and not getting the correct result.

How do i do this in PHP ?

For example: The two’s complement of E2 is 1E.

Hi,

[php]<?php

$tests = [
‘E2’, ‘1e’, ‘aab’, ‘f32d’,
];

foreach ($tests as $hex) {
echo "$hex => ", hex_complement($hex), PHP_EOL;
}

function hex_complement($hex) {
$dec = hexdec($hex);
$clear = dechex($dec);
$big = ‘1’. str_repeat(‘0’, strlen($clear));
$comp = hexdec($big) - $dec;

return strtoupper(dechex($comp));

}[/php] results E2 => 1E 1e => E2 aab => 555 f32d => CD3

Is this the correct result?

thx,

what i an wondering, would this do the same, or would i run into troubles somehow?

[php]
$dec = (int) 226;
$negative = $dec * -1;
echo dechex( bindec( ltrim( decbin( $negative ) , ‘1’) ) );
[/php]

hi,

would i run into troubles somehow?
i suppose yes

[php]$dec = hexdec(‘1E’);
$negative = $dec * -1;
echo dechex( bindec( ltrim( decbin( $negative ) , ‘1’) ) ); // outputs ‘2’ instead of ‘E2’[/php]

ltrim too greedy and removes extra bits

Sponsor our Newsletter | Privacy Policy | Terms of Service