2011. május 16., hétfő

Delphi Undocumented: Using BinToHex and HexToBin


Undocumented BinToHex and HexToBin ?


procedure BinToHex(Buffer, Text: PChar; BufSize: Integer);
function HexToBin(Text, Buffer: PChar; BufSize: Integer): Integer;

Many VCL and Windows API routines require TPoint or TRect records. To save declaring local variables and filling in the fields, you can use the set of routines declared in this unit. Point takes an X and Y co-ordinate, and produces a TPoint. Rect takes the left, top, right and bottom co-ordinates of a rectangle and manufactures a TRect record. Bounds is very similar to Rect but takes left, top, width and height information.

In Delphi 4 (and later), you will also find the undocumented BinToHex and HexToBin. These translate between binary data and a textual representation of it. They exist in all versions of Delphi, but Delphi 4 is the first to surface them outside the unit.

For example, an Extended variable is 10 bytes in size. Each byte is represented as two hexadecimal characters, so 20 characters are needed to display its contents in pure text. Listing 8 translates the 10 bytes of an Extended into a string (PChar) and then back again.

Using BinToHex and HexToBin

//Buffer is binary data,
//Text is target text buffer (assumed to be big enough),
//BufSize is size of binary data block
//procedure BinToHex(Buffer, Text: PChar; BufSize: Integer);

//Text is textual representation of binary data,
//Buffer is target binary data buffer
//BufSize is size of textual data buffer
//function HexToBin(Text, Buffer: PChar; BufSize: Integer): Integer;

procedure TForm1.Button1Click(Sender: TObject);
  E: Extended;
  //Make sure there is room for null terminator
  Buf: array[0..SizeOf(Extended) * 2] of Char;
  E := Pi;
  Label1.Caption := Format('E starts off as %.15f', [E]);
  BinToHex(@E, Buf, SizeOf(E));
  //Slot in the null terminator for the PChar, so we can display it easily
  Buf[SizeOf(Buf) - 1] := #0;
  Label2.Caption := Format('As text, the binary contents of E look like %s', [Buf]);
  //Translate just the characters, not the null terminator
  HexToBin(Buf, @E, SizeOf(Buf) - 1);
  Label3.Caption := Format('Back from text to binary, E is now %.15f', [E]);

Nincsenek megjegyzések:

Megjegyzés küldése