Reputation: 39
In an incoming UDP packet I have the hex value b70500
. This is actually a sequence number (1463
). I need to increment this value before sending it back to the server in the same format (b80500
).
How can I, in PHP, increment the value by one?
Using the code suggested here I was able to convert the hex value to an integer and increment it by one:
$original_hex = 'b70500'; // 1463
$original_int = unpack("H*", strrev(pack("H*", $original_hex))); // 0005b7
$incremented_int = hexdec($original_int[1]) + 1; // 1464
$incremented_hex = ? // Expected result: b80500
... But I have no idea how to convert it back into hex. Perhaps there is a more efficient method?
Upvotes: 2
Views: 2219
Reputation: 39
It's not pretty and I bet there are more efficient ways of doing this, but it works:
function increment_hex($hex) {
$original_hex = $hex;
$original_int = unpack("H*", strrev(pack("H*", $original_hex)));
$incremented_int = hexdec($original_int[1]) + 1;
$incremented_hex = dechex($incremented_int);
$padded_hex = str_pad($incremented_hex, 6, '0', STR_PAD_LEFT);
$reversed_hex = unpack("H*", strrev(pack("H*", $padded_hex)));
return $reversed_hex[1];
}
echo "result: " . increment_hex('b70500') . "\n";
result: b80500
Upvotes: 1
Reputation: 13283
hexdec()
and dechex()
. You do not have to unpack the value.
$incremented = dechex(hexdec('b70500') + 1);
Upvotes: 2