phpalgorithmcharacter-encodingparity7-bit

how to convert a character to 7 bit even parity in php


I want to convert a Character to a 7 bit even parity. Can you please suggest me, how to implement this?


Solution

  • Too bad you can't use the x86 JPO instruction (Jump if Parity Odd) ;-)

    Depending on the amount of data you want to handle it might be faster if you first set up a translation table than to check/handle character by character.

    $map = array();
    for($char=0; $char<128; $char++) {
      $parity = 0;
      for($bit=0; $bit<8; $bit++) {
        if($char & (1<<$bit)) {
          $parity ^= 128;
        }
      }
      $map[chr($char)] = chr($char|$parity);
    }
    

    (you might want to test this code thoroughly, I haven't)
    and then use strtr() to translate from ascii7 to ascii7-evenbit.

    $input = 'mary had a little lamb'; // all characters must be within the ascii7 range
    $evenbit = strtr($input, $map);
    // test output
    for($i=0; $i<strlen($evenbit); $i++) {
      printf("%08s\n", decbin(ord($evenbit[$i])));
    }