I want to convert a Character to a 7 bit even parity. Can you please suggest me, how to implement this?
how to convert a character to 7 bit even parity in php
2.2k views Asked by Nidhin Baby At
3
There are 3 answers
0
On
At the risk of downvotes:
function to7BitEven($byte) {
if( $byte > 0x7f ) return 0;
$binary = decbin($byte);
$one = 0;
$ret = 0;
for($x=0;$x<strlen($binary);$x++) {
if( $binary[$x] == '1' ) $one++;
}
if( $one % 2 != 0 ) $ret = "1";
else $ret = "0";
for($x=0;$x<(7-strlen($binary));$x++)
$ret .= "0";
$ret .= $binary;
return $ret;
}
echo to7BitEven(0x7f) . "\n";
echo to7BitEven(0x41) . "\n";
echo to7BitEven(0x3a) . "\n";
echo to7BitEven(0x3b) . "\n";
This will count the 1's, and add an extra 1 (if odd) or a 0 (if even) to the first bit. Then copy the other 7 bits into the return. This will leave you with a string representation of the 7 bit, even parity of the byte.
To those more experienced then I, does this look right? Example output:
11111111
01000001
00111010
10111011
0
On
Here's a C version:
uint8_t even_parity (uint8_t b)
{
return b ^ ((3459840 >> ((b ^ (b >> 4)) & 15)) & 128);
}
I'm sure translation to PHP would be easy, but I'll avoid embarrassing myself.
Inspired by this Bit Twiddling Hack.
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.
(you might want to test this code thoroughly, I haven't)
and then use strtr() to translate from ascii7 to ascii7-evenbit.