I want to convert a Character to a 7 bit even parity. Can you please suggest me, how to implement this?
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
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])));
}
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.