Advertisement
roozgar

crc16 delphi android

Jul 18th, 2019
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Pascal 2.16 KB | None | 0 0
  1. function BinToDec(Str: string): Integer;
  2. var
  3.   Len, Res, i: Integer;
  4.   Error: Boolean;
  5. begin
  6.   Error:=False;
  7.   Len:=Length(Str);
  8.   Res:=0;
  9.   for i:=0 to Len-1 do
  10.     if (Str[i]='0')or(Str[i]='1') then
  11.       Res:=Res+Pow(2, Len-i)*StrToInt(Str[i])
  12.     else
  13.     begin
  14.       Error:=True;
  15.       Break;
  16.     end;
  17.   if Error=True then Result:=0
  18.     else Result:=Res;
  19. end;
  20. //------------------------------------------------------------------------------
  21. function CRC16CCITT(bytes: array of Byte): Word;
  22. const
  23.   polynomial = $1021;
  24. var
  25.   crc: Word;
  26.   I, J: Integer;
  27.   b: Byte;
  28.   bit, c15: Boolean;
  29. begin
  30.   crc := $FFFF;
  31.   for I := 0 to High(bytes) do
  32.   begin
  33.     b := bytes[I];
  34.     for J := 0 to 7 do
  35.     begin
  36.       bit := (((b shr (7-J)) and 1) = 1);
  37.       c15 := (((crc shr 15) and 1) = 1);
  38.       crc := crc shl 1;
  39.       if ((c15 xor bit) <> false) then crc := crc xor polynomial;
  40.     end;
  41.   end;
  42.   Result := crc and $ffff;
  43. end;
  44. //------------------------------------------------------------------------------
  45. function bin2crc16(str: string): string;
  46. var
  47. I:integer;
  48. lengthCount : integer;
  49. crcByteArr : array of Byte;
  50. crcOut : Word;
  51. begin
  52.   lengthCount := Trunc(length(str)/8);
  53.   setlength(crcByteArr , lengthCount );
  54.   for I := 0 to lengthCount-1 do
  55.   begin
  56.     crcByteArr[I] := BinToDec(copy(str, I*8, 8));
  57.   end;
  58.   crcOut := CRC16CCITT(crcByteArr);
  59.  
  60.   result := crcOut.ToHexString;
  61.  
  62. end;
  63. //-----------------------------------------------------------------------------------
  64. function HexToBin(Hexadecimal: string): string;
  65. const
  66.   BCD: array [0..15] of string =
  67.     ('0000', '0001', '0010', '0011', '0100', '0101', '0110', '0111',
  68.     '1000', '1001', '1010', '1011', '1100', '1101', '1110', '1111');
  69. var
  70.   i: integer;
  71. begin
  72.   //form2.Memo4.Lines.Add('xin'+Hexadecimal);
  73.   Result := '';
  74.   for i := Length(Hexadecimal) downto 1 do
  75.     Result := BCD[StrToInt('$' + Hexadecimal[i])] + Result;
  76. end;
  77. //---------------------------------------------------------------------------------
  78. function Pow(i, k: Integer): Integer;
  79. var
  80.   j, Count: Integer;
  81. begin
  82.   if k>0 then j:=2
  83.     else j:=1;
  84.   for Count:=1 to k-1 do
  85.     j:=j*2;
  86.   Result:=j;
  87. end;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement