Mega Code Archive

 
Categories / Delphi / Examples
 

IntToHex Counterparts (HexToInt,IntToBin and BinToInt)

Title: IntToHex Counterparts (HexToInt,IntToBin and BinToInt) Question: Delphi kindly gave us IntToHex, but forgot to supply it's counterpart HexToInt. Also no binary functions are in the sysutils unit, IntToBin and BinToInt. Here's how to implement the missing functionality. Uses Delphi 5 Int64 type but can be modified for all Delphi versions. Answer: { ======================================= } { Convert a HexString value to an Int64 } { Note : Last Char can be 'H' for Hex } { eg. '00123h' or '00123H' } { 0 will be returned if invalid HexString } { ======================================= } function HexToInt(HexStr : string) : Int64; var RetVar : Int64; i : byte; begin HexStr := UpperCase(HexStr); if HexStr[length(HexStr)] = 'H' then Delete(HexStr,length(HexStr),1); RetVar := 0; for i := 1 to length(HexStr) do begin RetVar := RetVar shl 4; if HexStr[i] in ['0'..'9'] then RetVar := RetVar + (byte(HexStr[i]) - 48) else if HexStr[i] in ['A'..'F'] then RetVar := RetVar + (byte(HexStr[i]) - 55) else begin Retvar := 0; break; end; end; Result := RetVar; end; { ============================================== } { Convert an Int64 value to a binary string } { NumBits can be 64,32,16,8 to indicate the } { return value is to be Int64,DWord,Word } { or Byte respectively (default = 64) } { NumBits normally are only required for } { negative input values } { ============================================== } function IntToBin(IValue : Int64; NumBits : word = 64) : string; var RetVar : string; i,ILen : byte; begin RetVar := ''; case NumBits of 32 : IValue := dword(IValue); 16 : IValue := word(IValue); 8 : IValue := byte(IValue); end; while IValue 0 do begin Retvar := char(48 + (IValue and 1)) + RetVar; IValue := IValue shr 1; end; if RetVar = '' then Retvar := '0'; Result := RetVar; end; { ============================================== } { Convert a bit binary string to an Int64 value } { Note : Last Char can be 'B' for Binary } { eg. '001011b' or '001011B' } { 0 will be returned if invalid BinaryString } { ============================================== } function BinToInt(BinStr : string) : Int64; var i : byte; RetVar : Int64; begin BinStr := UpperCase(BinStr); if BinStr[length(BinStr)] = 'B' then Delete(BinStr,length(BinStr),1); RetVar := 0; for i := 1 to length(BinStr) do begin if not (BinStr[i] in ['0','1']) then begin RetVar := 0; Break; end; RetVar := (RetVar shl 1) + (byte(BinStr[i]) and 1) ; end; Result := RetVar; end;