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.

3
  • 1
    works out of the box.3v4l.org/g1ggf php.net/manual/en/… Commented Oct 5, 2017 at 14:06
  • 1
    PHP supports 0x... notation natively for an integer variable, but if you've got a string that you've received from an API, you'll need to run it through hexdec() Commented Oct 5, 2017 at 14:10
  • Can one of you post these as an answer? Commented Oct 5, 2017 at 14:30

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.