PHP Hex to Integer

4

I'm integrating a PHP application with an API that uses permissions in the form of 0x00000008, 0x20000000, etc. where each of these represents a given permission. Their API returned an integer. In PHP, how do I interpret something like 0x20000000 into an integer so I can utilize bitwise operators?

Another dev told me he thought these numbers were hex annotation, but googling that in PHP I'm finding limited results. What kind of numbers are these and how can I take an integer set of permissions and using bitwise operators determine if the user can 0x00000008.

php
asked on Stack Overflow Oct 5, 2017 by Webnet

2 Answers

3

As stated in the php documentation, much like what happens in the C language, this format is recognized in php as a native integer (in hexadecimal notation).

<?php
echo 0xDEADBEEF; // outputs 3735928559

Demo : https://3v4l.org/g1ggf

Ref : http://php.net/manual/en/language.types.integer.php#language.types.integer.syntax

Thus you could perform on them any bitwise operation since they are plain integers, with respect to the size of the registers on your server's processor (nowadays you are likely working on a 64-bit architecture, just saying in case it applies, you can confirm it with phpinfo() and through other means in doubt).

echo 0x00000001<<3; // 1*2*2*2, outputs 8

Demo : https://3v4l.org/AKv7H

Ref : http://php.net/manual/en/language.operators.bitwise.php

As suggested by @iainn and @SaltyPotato in their respective answer and comment, since you are reading the data from an API you might have to deal with these values obtained as strings instead of native integers. To overcome this you would just have to go through the hexdec function to convert them before use.

Ref : http://php.net/manual/en/function.hexdec.php

answered on Stack Overflow Oct 5, 2017 by Calimero • edited Oct 5, 2017 by Calimero
2

Since you are receiving it from an API php will interpret it as a string

echo hexdec('0x00000008');

returns the integer 8

This should work.

answered on Stack Overflow Oct 5, 2017 by SaltyPotato

User contributions licensed under CC BY-SA 3.0