Need to do a 8-Bit Fletcher Algorithm checksum.
Mostrar comentarios más antiguos
I have to sent serial command to a gps receiver but it is necessary create 2 checksum bytes after all commands.
The receiver protocol is the 8-bit Fletcher.
The number of bytes in the message can be variable. The algorithme in an other language is:
%%%%%%%%%
CK_A = 0, CK_B = 0
For(I=0;I<N;I++)
{
CK_A = CK_A + Buffer[I]
CK_B = CK_B + CK_A
}
%%%%%%%%%%
I'would not prefare use the famous 'dec2bin' if possible
thank you
Respuestas (1)
Rushil
el 24 de En. de 2025
Hi Patrice
From the provided implementation, I assume that the buffer is a sequence of 8-bit integers for which we need to compute the checksums. We can use MATLAB to easily accomplish this task using “mod” function (to retain the 8-bit nature of the integers). Below you will find implementation of the same:
function [CK_A, CK_B] = fletcher(Buffer)
CK_A = uint8(0);
CK_B = uint8(0);
N = length(Buffer);
for I = 1:N
% use mod with 2^8 (which is 256)
CK_A = mod(CK_A + uint8(Buffer(I)), 256);
CK_B = mod(CK_B + CK_A, 256);
end
end
% an example of using it
Buffer = [1, 2, 3, 4, 5, 6];
[CK_A, CK_B] = fletcher(Buffer)
To help with understanding the function, you may find the documentation of “mod” below:
Hope it helps you out
larush
3 comentarios
Walter Roberson
el 24 de En. de 2025
Not quite. You are adding two uint8 values. When the result of adding two uint8 values would overflow uint8 the result saturates to become uint8(255) . There is no point using mod(256) on the addition of two uint8 values because the result always saturates at most 255. Which is not what you want happening.
So instead you need to use uint16 for the calculations.
function [CK_A, CK_B] = fletcher(Buffer)
CK_A = uint16(0);
CK_B = uint16(0);
N = length(Buffer);
for I = 1:N
% use mod with 2^8 (which is 256)
CK_A = mod(CK_A + uint16(Buffer(I)), 256);
CK_B = mod(CK_B + CK_A, 256);
end
CK_A = uint8(CK_A);
CK_B = uint8(CK_B);
end
% an example of using it
Buffer = [1, 2, 3, 4, 5, 6];
[CK_A, CK_B] = fletcher(Buffer)
This code does assume that the input Buffer has no elements greater than 255.
Rushil
el 24 de En. de 2025
Hi Walter
Thanks for the response. I may have overlooked this fact, since I am used to using macros in C++.
#define int long long
Usually most operations (multiplication too) performed modulo some 32-bit number work, since the 64-bit operations allow the operations on large integers, which would otherwise overflow. I guess this is a good opportunity for me to learn more about this in MATLAB.
Your comment helps not only 1, but 2 people, thank you for the clarification.
larush
patrice boisset
el 29 de En. de 2025
Categorías
Más información sobre Speech Recognition en Centro de ayuda y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!