Chinaunix首页 | 论坛 | 博客
  • 博客访问: 355669
  • 博文数量: 101
  • 博客积分: 4714
  • 博客等级: 大校
  • 技术积分: 1725
  • 用 户 组: 普通用户
  • 注册时间: 2006-10-01 04:51
文章分类

全部博文(101)

文章存档

2011年(1)

2010年(98)

2008年(2)

分类:

2010-01-03 15:54:44

 

{
    Use TStringStream as a buffer, you can use this unit to read/write byte, word, or integer values.
}

unit BufferReader;

interface

uses
    Classes, Windows;

type
  TValueType = (vtInt8, vtInt16, vtInt32);

  TBufferReader = class(TStringStream)
  private
    function RevertValue(Value: Integer): Integer;
    function GetValueTypeLen(ValueType: TValueType): Integer;
  public
    function ReadValue(ValueType: TValueType): Integer;
    procedure WriteValue(Value: Integer; ValueType: TValueType);
  end;


implementation

{ TBufferReader }

function TBufferReader.GetValueTypeLen(ValueType: TValueType): Integer;
begin
    case ValueType of
        vtInt8: Result := 1;
        vtInt16: Result := 2;
    else
        Result := 4;
    end;
end;

procedure TBufferReader.WriteValue(Value: Integer; ValueType: TValueType);
begin
    Value := RevertValue(Value);
    Write(Value, GetValueTypeLen(ValueType));
end;

function TBufferReader.ReadValue(ValueType: TValueType): Integer;
var
    Value: Integer;
begin
    Read(Value, GetValueTypeLen(ValueType));
    Result := RevertValue(Value);
end;

function TBufferReader.RevertValue(Value: Integer): Integer;
var
    HiWord, LoWord: Word;
    HiByte, LoByte: Byte;
begin
    LoWord := Value and $FFFF;
    HiWord := (Value and $FFFF0000) shr 16;

    LoByte := LoWord and $FF;
    HiByte := (LoWord and $FF00) shr 8;
    if DWORD(Value) <= $FF then
        LoWord := LoByte
    else
        LoWord := (LoByte shl 8) or HiByte;

    LoByte := HiWord and $FF;
    HiByte := (HiWord and $FF00) shr 8;
    HiWord := (LoByte shl 8) or HiByte;

    if DWORD(Value) <= $FFFF then
        Result := LoWord
    else
        Result := (LoWord shl 16) or HiWord;
end;

end.


阅读(2381) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~