Looking at the numpy reference, I found a useful function for bit processing, so I also implemented a Hamming code for testing. For the time being, only the Hamming code (4,3) is supported. I wish I could support other than uint8.
hamming.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
import random
if __name__ == '__main__':
k = 4
m = 3
#Create a list of non-powers of 2
column_values = np.array([ [x] for x in range( 2 ** m ) if ( x & ( x - 1 ) ) != 0 ], dtype=np.uint8 )
A = np.reshape( np.unpackbits( column_values ), ( k, 8) )[:, -3:].T
#Create generator and check matrices
H = np.concatenate( ( A, np.eye( m, dtype=np.uint8 ) ), axis=1 )
G = np.concatenate( ( np.eye( k, dtype = np.uint8 ), A.T ), axis = 1 )
#Appropriately set the value to be encoded
random.seed()
code = random.randint( 0, 2 ** k - 1 )
bit_code = np.unpackbits( np.array( code, dtype = np.uint8 ) )[-k:]
#Generate a Hamming code to invert a bit
error_bit_offset = random.randint( 0, ( k + m ) - 1 )
hamming_code = np.dot( bit_code, G ) % 2
hamming_code[ error_bit_offset ] = ( hamming_code[ error_bit_offset ] + 1 ) % 2
#Verification
check_result = np.dot( H, hamming_code ) % 2
print code
print hamming_code
print H
print error_bit_offset
print check_result
Execution result
% ./hamming.py
12
[1 0 0 0 1 1 0]
[[0 1 1 1 1 0 0]
[1 0 1 1 0 1 0]
[1 1 0 1 0 0 1]]
1
[1 0 1]
Recommended Posts