May 13, 2013

Is there a way to perform binary math on binary strings in PHP?

Skyline969’s Question:

I’m working with some numbers that would be far too large for PHP to handle (IPv6 addresses in binary), so to work around this I’ve formulated a function to convert the addresses to/from binary strings (literally just a string of 1s and 0s). However, when it comes to subnet calculations the easiest way I know how to do this is to use binary math. I have no idea how I’d use binary math in this instance since I’m technically dealing with strings, not binary numbers. Is there any way I can do binary math with a string representation of a binary number?

How about going simple and converting binary to decimal then performing operations on it, then changing it back to binary?

Reference: bindec(), decbin()

Simple Example:

$a = 110;
$b = 101;

$add = bindec($a) + bindec($b);
$binadd = decbin($add); //after done change it back

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!