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