1 | unit UDynNumber;
|
---|
2 |
|
---|
3 | {$mode objfpc}{$H+}
|
---|
4 |
|
---|
5 | interface
|
---|
6 |
|
---|
7 | uses
|
---|
8 | Classes, SysUtils, UBitStream, Math;
|
---|
9 |
|
---|
10 | type
|
---|
11 |
|
---|
12 | { TDynamicNumber }
|
---|
13 |
|
---|
14 | TDynamicNumber = class
|
---|
15 | Stream: TBitStream;
|
---|
16 | procedure WriteNumber(Value: QWord);
|
---|
17 | function ReadNumber: QWord;
|
---|
18 | constructor Create;
|
---|
19 | destructor Destroy; override;
|
---|
20 | private
|
---|
21 | function ReadNumber2: QWord;
|
---|
22 | end;
|
---|
23 |
|
---|
24 | implementation
|
---|
25 |
|
---|
26 | { TDynamicNumber }
|
---|
27 |
|
---|
28 | procedure TDynamicNumber.WriteNumber(Value: QWord);
|
---|
29 | var
|
---|
30 | Length: Integer;
|
---|
31 | begin
|
---|
32 | Length := Floor(Log2(Value)) + 1;
|
---|
33 | if Length > 1 then begin
|
---|
34 | Stream.WriteNumber(1, 1);
|
---|
35 | WriteNumber(Length - 2);
|
---|
36 | end else Stream.WriteNumber(0, 1);
|
---|
37 | if Length > 1 then Length := Length - 1;
|
---|
38 | Stream.WriteNumber(Value, Length);
|
---|
39 | end;
|
---|
40 |
|
---|
41 | function TDynamicNumber.ReadNumber: QWord;
|
---|
42 | var
|
---|
43 | Bit: Byte;
|
---|
44 | Length: Integer;
|
---|
45 | begin
|
---|
46 | Length := 0;
|
---|
47 | Bit := Stream.ReadNumber(1);
|
---|
48 | if Bit = 0 then Length := 1
|
---|
49 | else Length := ReadNumber2 + 2;
|
---|
50 | if Length > 1 then Result := Stream.ReadNumber(Length - 1)
|
---|
51 | else Result := Stream.ReadNumber(Length);
|
---|
52 | if Length > 1 then Result := Result or (QWord(1) shl (Length - 1));
|
---|
53 | end;
|
---|
54 |
|
---|
55 | function TDynamicNumber.ReadNumber2: QWord;
|
---|
56 | var
|
---|
57 | Bit: Byte;
|
---|
58 | Length: Integer;
|
---|
59 | begin
|
---|
60 | Length := 0;
|
---|
61 | Bit := Stream.ReadNumber(1);
|
---|
62 | if Bit = 0 then Length := 1
|
---|
63 | else Length := ReadNumber + 2;
|
---|
64 | if Length > 1 then Result := Stream.ReadNumber(Length - 1)
|
---|
65 | else Result := Stream.ReadNumber(Length);
|
---|
66 | if Length > 1 then Result := Result or (QWord(1) shl (Length - 1));
|
---|
67 | end;
|
---|
68 |
|
---|
69 | constructor TDynamicNumber.Create;
|
---|
70 | begin
|
---|
71 | Stream := TMemoryBitStream.Create;
|
---|
72 | end;
|
---|
73 |
|
---|
74 | destructor TDynamicNumber.Destroy;
|
---|
75 | begin
|
---|
76 | Stream.Free;
|
---|
77 | inherited Destroy;
|
---|
78 | end;
|
---|
79 |
|
---|
80 | end.
|
---|
81 |
|
---|