Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // AndrewMohawk
- // http://www.andrewmohawk.com
- /* Decode Track 2/3 data from binary */
- $binary = "<yourBinaryHere>";
- // this function by mtroy dot student at gmail dot com taken from http://php.net/manual/en/function.strpos.php
- function strpos_r($haystack, $needle)
- {
- if(strlen($needle) > strlen($haystack))
- trigger_error(sprintf("%s: length of argument 2 must be <= argument 1", __FUNCTION__), E_USER_WARNING);
- $seeks = array();
- while($seek = strrpos($haystack, $needle))
- {
- array_push($seeks, $seek);
- $haystack = substr($haystack, 0, $seek);
- }
- return $seeks;
- }
- function processBinary($binary)
- {
- $AsciiOutput = "";
- //find start sentinal
- $start_sentinal = strpos($binary,"11010");
- if($start_sentinal === false)
- {
- echo "Could not find start sentinal\n";
- return false;
- }
- //find end sentinal
- $end_sentinal = false;
- $end_sentinals = strpos_r($binary,"11111");
- if(count($end_sentinals) == 0)
- {
- echo "Could not find end sentinal\n";
- return false;
- }
- //Check end sentinal is on a 5 bit boundry
- foreach($end_sentinals as $es)
- {
- $es = $es;
- if(($es - $start_sentinal) % 5 == 0)
- {
- $end_sentinal = $es;
- }
- }
- if($end_sentinal == false)
- {
- echo "End sentinal not on correct boundry\n";
- return false;
- }
- //Lets decode the data:
- $bit_length = 5; // 4 bits for data, 1 bit for odd-parity or LRC checking
- $data = substr($binary,$start_sentinal,($end_sentinal-$start_sentinal+5));
- $currentBits = "";
- $currentNum = 0;
- $finalString = "";
- for($i=0;$i<strlen($data);$i++)
- {
- if(strlen($currentBits) < $bit_length)
- {
- $currentBits .= $data[$i];
- }
- if(strlen($currentBits) == $bit_length)
- {
- $parityBit = $currentBits[4];
- $dataBits = substr($currentBits,0,4);
- $asciiChar = 0;
- for($x=0;$x<4;$x++)
- {
- $currentNum += $dataBits[$x];
- }
- $dec = bindec($dataBits);
- $dec = str_pad($dec, 2, "0", STR_PAD_LEFT); // just so output is nice
- $asciiChar = chr(bindec(strrev($dataBits))+48); // reverse the binary (since its LSB first) then convert to dec, add 48 and then take it to ASCII
- echo "$currentBits - Data ($dataBits) Parity($parityBit) Decimal ($dec) Ascii($asciiChar)";
- if(($currentNum + $parityBit) % 2 == false)
- {
- echo " __ Parity: Invalid";
- }
- else
- {
- echo " __ Parity: Valid";
- }
- $AsciiOutput .= $asciiChar;
- echo "\n";
- $currentBits = "";
- $currentNum = 0;
- }
- }
- echo "\n\nTotal Out (ascii): $AsciiOutput\n";
- }
- echo "Trying One way:\n\n";
- if (processBinary($binary) == false)
- {
- //reverse.
- echo "\n\n";
- echo "Trying The Reverse:\n\n";
- processBinary(strrev($binary));
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement