0

Using bit shift, it is easy to do for 2 ids as follows:

$id1 = 125;
$id2 = 23;
$mergedid = ($id1 << 8) + $id2

then to obtain each id:

$id1 = $mergedid >> 8;
$id2 = $mergedid & 0xFF;

Anyonw knows how to do for 3 or more ids?

user2707590
  • 1,066
  • 1
  • 14
  • 28
  • Why not using an array or any data structure that is designed to hold multiple data? – Freddy May 15 '16 at 15:53
  • 1
    How many more ids? Are you running 32-bit or 64-bit PHP? The answer to those question will make a big difference.... it's easy to bitshift 4x8bit ids in 32-bit PHP (`$mergedid = ($id1 << 24) + ($id2 << 16) +($id3 << 8) + $id4`, a lot harder to do more than 4x8bit in 32-bit PHP – Mark Baker May 15 '16 at 15:53
  • im on 64bit php. Ok let's do for 4 id and take the example that you gave. How do you retrieve each of the ids now? For the 2 ids example i gave, it's `$id2 = $mergedid & 0xFF;` but in your case how you do it? do you need to bit shift 1 by 1? @MarkBaker – user2707590 May 15 '16 at 16:11
  • @Freddy - could you atleast give example of what you are saying? – user2707590 May 15 '16 at 16:12
  • See the following link from the manual, it contains multiple examples http://php.net/manual/en/language.types.array.php – Freddy May 15 '16 at 16:15
  • 1
    `$id4 = $mergeid & 0xFF; $id3 = $mergeid >> 8 & 0xFF; $id2 = $mergeid >> 16 & 0xFF; $id1 = $mergeid >> 24 & 0xFF;` [Demo](https://3v4l.org/6DdsZ) – Mark Baker May 15 '16 at 16:20
  • ahh ok, i was stuck at this part and didn't know if we hav to `&` for every id. thanks – user2707590 May 15 '16 at 16:29

1 Answers1

1

Merge

$mergedid = ($id1 << 24) + ($id2 << 16) + ($id3 << 8) + ($id4 << 0)

Extract

$id1 = ($mergedid >> 24) & 0xFF;
$id2 = ($mergedid >> 16) & 0xFF;
$id3 = ($mergedid >>  8) & 0xFF;
$id4 = ($mergedid >>  0) & 0xFF;

I know left shifting and right shifting by 0 does nothing. I have just included it to show you the pattern

DollarAkshay
  • 2,063
  • 1
  • 21
  • 39
  • this is great. exactly what i was looking for. – user2707590 May 15 '16 at 16:30
  • i am having issues when integrating with my app. could you help em? the 4 ids have different limits. $id1 = (2^8)bits, $id2 = (2^12)bits, $id3 = (2^24) bits and $id4 = (2^32)bits... so my `$mergedid = ($id4 << 24) + ($id3 << 16) + ($id2 << 12) + ($id1 << 0);` but when i use the way you specified to fetch the ids, it does not return the correct result. – user2707590 May 15 '16 at 17:03
  • @user2707590 I think that would be a problem cause according to this http://stackoverflow.com/questions/670662/whats-the-maximum-size-for-an-int-in-php The maximum number of bits an integer can hold is either 32 bits or 64 bits. Anything more than that would cause problems – DollarAkshay May 15 '16 at 17:08
  • 1
    32 + 24 + 12 + 8 = 76 ... its over 64 bits – DollarAkshay May 15 '16 at 17:16