%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