티스토리 뷰

Programming/Delphi

Delphi - StrToBin, StringToHex, HexToString

파란크리스마스 2009. 5. 1. 06:09
728x90

출처 : http://www.xxlinux.com/linux/dev/Delphi/2007-10-30/11392.html
http://dolba.net/old_k2club/bbs/bbs.php3?board=delphi&mode=view&id=345&page=32&recnum=359&keyword=&flag=
http://www.pic16.com/BBS/dispbbs.asp?boardID=31&ID=17357&page=3

function StrToBin(const S: string): string;
const
  BitArray: array[0..15] of string =
      ('0000', '0001', '0010', '0011',
       '0100', '0101', '0110', '0111',
       '1000', '1001', '1010', '1011',
       '1100', '1101', '1110', '1111');
var
  Index: Integer;
  LoBits: Byte;
  HiBits: Byte;
begin
  Result := '';
  for Index := 1 to Length(S) do
  begin
      HiBits := (Byte( S[Index]) and $F0) shr 4;
      LoBits := Byte( S[Index]) and $0F;
      Result := Result + BitArray[HiBits];
      Result := Result + BitArray[LoBits];
  end;
end;

function StringToHex(const S: string): string;
var
  Index: Integer;
begin
  Result := '';
  for Index := 1 to Length(S) do
    Result := Result + IntToHex( Byte( S[Index] ), 2 );
end;

function TransChar(AChar: Char): Integer;
begin
  if AChar in ['0'..'9'] then
  Result := Ord(AChar) - Ord('0')
  else
  Result := 10 + Ord(AChar) - Ord('A');
end;

function HexToString(aHex: String): String;
var
  I : Integer;
  CharValue: Word;
begin
  Result := '';
  for I := 1 to Trunc(Length(aHex)/2) do begin
    Result := Result + ' ';
    CharValue := TransChar(aHex[2*I-1])*16 + TransChar(aHex[2*I]);
    Result[I] := Char(CharValue);
  end;
end;

procedure TForm1.Button3Click(Sender: TObject);
begin
  ShowMessage(
    '한글'' Hex Code is ' + StringToHex('한글') + chr(13) +
    '한글'' Binary Code is ' + StrToBin('한글') + chr(13) +
    '한글'' HexToString ' + HexToString(StringToHex('한글'))
  );
end;

댓글
300x250
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함