hexadecimal calculating: turning on the high bit
- From: HanslH <no@xxxxx>
- Date: Wed, 22 Nov 2006 21:10:16 +0100
Communicating (serial) from delphi with a device I have to conform to
some format.
One of the rules is that a two byte trailer should consist of a
checksum byte and an end byte (always 0x03)
I have to sum the value for every byte into an 'unsigned char' and
then ** turn on the high bit** to ensure that the value can never be
0x02 or 0x03 because these characters have special meaning.
I have hardly any experience with hexadecimal calculating and 'and'
'or' operators in bit calculations or whatever.
I find that all examples in the reference *but one* will be calculated
successfully by the following algorithm
//======================================
function VetmessageChecksum(vetmessage : string) : string;
var
i:integer;
cHex : string;
aDec : arrayofinteger;
iChecksum : integer;
begin
cHex := '';
//make sure it ends with a space because of easier looping
if lastchar(vetmessage) <> ' ' then vetmessage := vetmessage + ' ';
//turning a '23 4F 45 22' type of string into an array of integer
for i := 1 to length(vetmessage) do begin
if (vetmessage[i]) = ' ' then begin
aadd(aDec,strtoint('$' + trim(cHex)));
cHex := '';
end else
cHex := cHex + vetmessage[i];
end;
//summing the value
iChecksum := 0;
for i := 0 to length(aDec) -1 do iChecksum := iChecksum + aDec[i];
/next ensures the *unsigned* char thing?
//I'm no expert but it's a trial and error assumption
iChecksum := iChecksum mod 256;
result := inttohex(iChecksum,2);
end;
//========================================
I find that the only example that doesnt compute right the checksum
byte is calculated '1d' but should be '9d'
All other example checksums the checksum byte starts with a hexdigit >
7
Am I right to assume that turning on the high bit means that I have to
add 8 to the first hexdigit if it's 7 or less?
.
- Follow-Ups:
- Re: hexadecimal calculating: turning on the high bit
- From: Rob Kennedy
- Re: hexadecimal calculating: turning on the high bit
- From: Erik
- Re: hexadecimal calculating: turning on the high bit
- Prev by Date: Re: More accurate Timerevent
- Next by Date: Re: hexadecimal calculating: turning on the high bit
- Previous by thread: Can't use TComponent in thread object?
- Next by thread: Re: hexadecimal calculating: turning on the high bit
- Index(es):
Relevant Pages
|