function crc_value = crc_16(text)
% CRC_16 is a function with the objective of converting a text input into
% the respective CRC-CCITT code(outputed by crc_value). It uses as an
% initialization value 0xFFFF, and the standard CCITT polynomial:
% x^16 + x^12 + x^5 + 1
% It is worth noting that both the initial value and the polynomial can be
% easily changed in the code
% Initializing the most imoportant parameters
crc_value = 0xFFFF; % initial value
poly = 0x1021; % polynomial
text_length = strlength(text);
xor_flag = false;
for i=1:text_length
ch = uint16(text(i)); % initializing the character to go
ch = bitshift(ch,8); % through each iteration
% CRC bitwise operations
for n=1:8
if bitand(bitxor(crc_value,ch),0x8000)
xor_flag = true;
else
xor_flag = false;
end
crc_value = bitshift(crc_value,1);
if xor_flag
crc_value = bitxor(crc_value,poly);
end
ch = bitshift(ch,1);
end
end
% Converting the final value into an hexadecimal vector of characters
crc_value = dec2hex(crc_value); % comment if no conversion is necessary
%crc_value = string(crc_value); % uncomment to convert into MATLAB string
end
The code is based on the C source code in https://srecord.sourceforge.net/crc16-ccitt.html, the "bad_crc" part of the code. The algorithm is also known as CRC-16/CCITT-FALSE (I believe).
引用
Francisco (2025). CRC-16/CCITT function (https://www.mathworks.com/matlabcentral/fileexchange/127803-crc-16-ccitt-function), MATLAB Central File Exchange. に取得済み.
MATLAB リリースの互換性
作成:
R2023a
すべてのリリースと互換性あり
プラットフォームの互換性
Windows macOS Linuxタグ
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!