我们在MATLAB中定义一个类(class),包含了CRC生成函数和检验函数(囊括了常用的CRC多项式)
classdef CRC
properties
CRCbit_Len
polynomial
CRCgen
CRCdet
end
methods
function obj = CRC(CRCbit_Len) %(polynomial)
obj.CRCbit_Len = CRCbit_Len;
switch CRCbit_Len
case 0
obj.polynomial = [0];
case 1
obj.polynomial = [1 1];
case 2
obj.polynomial = [1 1 1];
case 3
obj.polynomial = [1 1 1 1];
case 4
obj.polynomial = [1 0 0 1 1]; % x^4 + x + 1
case 5
obj.polynomial = [1 0 0 1 0 1];
case 6
obj.polynomial = [1 0 0 0 0 1 1]; %1000001
case 7
obj.polynomial = [1 0 0 0 1 1 1 1];
case 8
obj.polynomial = [1 0 0 1 1 0 0 0 1];
case 9
obj.polynomial = [1 0 0 0 1 0 0 0 0 1];
case 10
obj.polynomial = [1 0 0 0 0 1 0 0 0 1 1];
case 11
obj.polynomial = [1 0 0 0 0 0 0 1 0 0 0 1];
case 12
obj.polynomial = [1 0 0 1 0 0 0 0 0 0 0 1 1];
case 13
obj.polynomial = [1 0 0 0 1 0 0 0 0 0 0 0 1 1];
case 14
obj.polynomial = [1 0 0 0 0 1 0 1 0 0 0 0 0 1 1];
case 15
obj.polynomial = [1 0 0 0 0 0 0 0 1 0 0 0 0 0 0 1];
case 16
obj.polynomial = [1 1 0 0 0 0 0 0 0 0 0 0 0 0 1 0 1];
case 24
obj.polynomial = [1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1];
otherwise
disp(["Please add the corresponding polynomial in binary form."]);
end
obj.CRCgen = crc.generator('Polynomial', obj.polynomial, ...
'InitialState', zeros(1, obj.CRCbit_Len), ...
'FinalXOR', zeros(1, obj.CRCbit_Len));
obj.CRCdet = crc.detector('Polynomial', obj.polynomial, ...
'InitialState', zeros(1, obj.CRCbit_Len), ...
'FinalXOR', zeros(1, obj.CRCbit_Len));
end
% generate CRC
function crcencoded_data = encode(obj, data)
crcencoded_data = generate(obj.CRCgen, data); % SourceCoding_Len x No_Active_Users
end
% detect CRC
function [crcdecoded_data, error_detected] = decode(obj, received_data)
[crcdecoded_data, error_detected] = detect(obj.CRCdet, received_data);
end
end
end
clc; clear all;
rng('default');
warning('off');
K0 = 12; % information bits
K_crc = 4; % crc bits length
N = 16; % coded length (omit here)
% Rate = (K0 + K_crc) / N;
Ka = 10; % packet number
% Preporcessing:
% interleaver and de-interleaver related: for row vector
interleaver_IDs = randperm(N);
[~, de_interleaver_IDs] = sort(interleaver_IDs);
interlv_func = @(Bits) Bits(:, interleaver_IDs); % Bits could be a matrix with size (packet_num x FEC_Len)
de_interlv_func = @(interlv_Bits) interlv_Bits(:, de_interleaver_IDs);
% invoke CRC class
CRC = CRC(K_crc);
% Transmission
% information bits
u0 = randi([0, 1], K0, Ka);
% append CRC
u = CRC.encode(u0); % (K0 + K_crc) x Ka
% interleaving
inlv_bits = interlv_func(encodedBits);
% omit encoding process and receiver procedure
% de-interleaving
deinlv_bits = de_interlv_func(inlv_bits );