Converting Hex string to binary string lazarus / 21-General ---------------------------------------------------------------------- Frogfather · 2021-12-16 10:53 Morning! I've woken up this morning with an irresistible urge to convert hex strings to binary.  This may of course have something to do with today's https://adventofcode.com/2021/day/16 puzzle I've used the Hex to bin method in this earlier forum post: https://fo rum.lazarus.freepascal.org/index.php/topic,32612.msg210421.html#msg210 421 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i procedure TmainForm.day16part1;var  HValue,BValue:PChar;  BBufSize:Integer;  inStr,outStr:String;  output:integer;   function HexToNibble(const hexvalue: char; out nibble: byte): boolean;inline;  begin    if hexvalue IN ['0'..'9'] then      nibble:=((ord(hexvalue)) and 15)    else if char(byte(hexvalue) or $20) IN ['a'..'f'] then      nibble:=((ord(hexvalue)+9) and 15)    else      Exit(False);    Result := True;  end;   function HexToBin(HexValue, BinValue: PChar; BinBufSize: Integer): Integer;  var    i,j : integer;    h,l : byte;  begin    i:=binbufsize;    while (i>0) do    begin      if not HexToNibble(hexvalue^, h) then        break;      inc(hexvalue);     if not HexToNibble(hexvalue^, l) then        break;      j := l + (h shl 4);      inc(hexvalue);       binvalue^:=chr(j);      inc(binvalue);      dec(i);    end;    result:=binbufsize-i;  end; //Above is code from the forum post. Below is my code.begin  inStr:='EE00D40C823060';  outStr:='';  HValue:=@inStr[1];  BValue:=@outStr;  BBufSize:=length(inStr)*4;  output:=HexToBin(HValue,bValue,bBufSize);  lbResults.items.add('input string '+inStr);  lbResults.items.add('output string '+outStr);end; Unfortunately this doesn't work - throws an unhelpful 'bad access' error. The main problem here is I don't really understand what's going on and therefore don't know how to resolve it. If anyone has a few minutes to supply a dummies guide to pointers I'd be most grateful! Cheers John C ---------------------------------------------------------------------- marcov · 2021-12-16 11:00 WHere do you allocate room for characters in outstr? You set it to empty, which is 0 chars. ---------------------------------------------------------------------- Frogfather · 2021-12-16 11:21 Hi Marcov, Thanks for the quick reply. I told you I didn't fully understand what I was doing  I've tried setLength(outStr, length(instr)*4) (on the assumption that each hex character will get converted to 4 binary characters)  but outstr is still empty after calling the HexToBin method. Also tried just setting it to a long line of spaces with the same result. Also I still get a 'bad access' error although this seems to happen after the method has finished (i.e. I can get to line 51 without error but continuing causes the error to be thrown. This also happens if I delete the two logging lines) ---------------------------------------------------------------------- avra · 2021-12-16 13:01 Not directly hex2bin, but FPC trunk now supports for example SomeOrdTypeVar.ToBinString, SomeOrdTypeVar.Bits[3] and SomeOrdTypeVar.Nibbles[1] (with customizable localized formats when new syshelpers unit is used). https://gitlab.com/freepascal.org/fpc/source/-/issues/39268 Actually, everything from BitHelpers is now part of FreePascal. ---------------------------------------------------------------------- bytebites · 2021-12-16 13:13 Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   HValue:=pchar(inStr);  BValue:=pchar(outStr); ---------------------------------------------------------------------- BobDog · 2021-12-16 15:02 Windows, perhaps Linux using 'c' instead of 'msvcrt.dll' Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i   function  ultoa(T:longint;F:pointer;sz:integer):pchar ;cdecl external 'msvcrt.dll' name '_ultoa'; function strtoul (s:pchar;b:pointer;L: longint):longint ;cdecl external 'msvcrt.dll' name 'strtoul';   function intToBase(N:longint;_base:byte):pchar; var   s:ansistring;    buffer:pchar;    begin    setlength(s,50);    buffer:=@s[1];    ultoa(n,buffer,_base);    exit(buffer)end;  function intFromBase(s:pchar;_base:byte):longint ;    begin    exit(strtoul(s,nil,_base));end; function hextobin(hx:ansistring):ansistring;var ans:ansistring;var t:longint;be gint:=intfrombase(pchar(hx),16);ans:=inttobase(t,2);exit(ans); end; va rnum,i:longint;hx:ansistring;ans:ansistring;beginfor i:=1 to 10 dobeginnum:=random(2147483647);writeln('number ',num);hx:=hexstr(num,8);writeln('hex of number ',hx);ans:=hextobin(hx);writeln('Bin from hex ',ans);writeln('check  ',intfrombase(pchar(ans),2));writeln;end;writeln('Press return to end . . .');readln; end. ---------------------------------------------------------------------- Frogfather · 2021-12-16 15:54 Thanks all for the very quick and detailed replies. For the purposes of the puzzle I've written my own method, but will certainly take a look at the examples posted later. Cheers John C ---------------------------------------------------------------------- Remy Lebeau · 2021-12-16 17:10 Quote from: Frogfather on December 16, 2021, 11:53:59 amI've woken up this morning with an irresistible urge to convert hex strings to binary. Are you aware that FreePascal has a HexToBin() function for that exact purpose? ---------------------------------------------------------------------- winni · 2021-12-16 18:46 Hi! Even simpler since the very early Pascal days: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var i,error : integer;...  val ('$FF',i,error);   Winni ---------------------------------------------------------------------- jollytall · 2021-12-16 19:28 Well, maybe a bit of overkill, but my longmath unit (https://forum.laz arus.freepascal.org/index.php/topic,20586.msg425903.html#msg425903) can handle any base between 2 and 16 in any length, even making calculations with them. A simple line can work: s := '%1' * '$123456789ABCDEF'; returning: s = '100100011010001010110011110001001101010111100110111101111' '%1' is simply 1, but the input is in base two, indicating that the result's natural format shall also be base 2 and '$123..' is a hexa number. The product is the same number, but because it is now natively base 2, when put in a string with the := assign operator, it gives a base2 string. ---------------------------------------------------------------------- winni · 2021-12-16 19:53 Hi! This can be done with only the system functions: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var err : integer;     i,k : Int64;     s : string;   ...   val ('%1',i,err);   val ('$123456789ABCDEF',k,err);   s :=  BinStr(i*k,64);           There are so many powerful functions in the system unit - often the stuff in the multiple units is redundand. Winni ---------------------------------------------------------------------- Frogfather · 2021-12-16 21:50 Quote from: Remy Lebeau on December 16, 2021, 06:10:39 pmQuote from: Frogfather on December 16, 2021, 11:53:59 amI've woken up this morning with an irresistible urge to convert hex strings to binary. Are you aware that FreePascal has a HexToBin() function for that exact purpose? Hi Remy, Yes, I was having some difficulty getting it to produce the correct output (or indeed any output) probably as I've mentioned earlier, due to my not quite understanding it. For the purposes of Advent of Code I've written my own which does what I want, but once I have some more free time (ha!) I'll try to replace it with the built in method. Cheers John C ---------------------------------------------------------------------- BobDog · 2021-12-17 00:09 Hello jollytall. converting from base to base where the base is a power of two follows an easy pattern. You step through 2^0(=1) from hex to bin and 2^4(=16) from bin to hex. inttobin and inttohex can be used with these steps. The answer is accumulative for large strings. Could you check the larger number with your library? Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i usesstrutils,sysutils; function TrimLeadingZeros(const S: string): string;var  I, L: Integer;begin  L:= Length(S);  I:= 1;  while (I < L) and (S[I] = '0') do Inc(I);  exit (Copy(S, I));end; function hex2bin(hx:ansistring):ansistring;var ans:ansistring='';var t,r:longint;err:integer;beginfor t:=1 to length(hx) do beginval('$'+midstr(hx,t,1),r,err);ans:=ans+inttobin(r,4);end;exit( TrimLeadingZeros(ans));end; function bin2hex(bn:ansistring):ansistring;var ans:ansistring='';var t,r:longint;err:integer;beginwhile (length(bn) mod 4 <>0) dobeginbn:='0'+bn;end;t:=-3;repeatt:=t+4;if t>length(bn) then break;val('%'+midstr(bn,t,4),r,err);ans:=ans+inttohex(r,1);until false ;exit(TrimLeadingZeros(ans));end;varhx,bn:ansistring;  beginhx:='12345 6789ABCDEF';writeln('hex ',hx);bn:=hex2bin(hx);writeln('bin ',bn);writeln('hex ',bin2hex(bn)); hx:=hx+hx;writeln;writeln('hex ',hx);bn:=hex2bin(hx);writeln('bin ',bn);writeln('hex ',bin2hex(bn));writeln('Press return to end . . .');readln;end. ---------------------------------------------------------------------- Frogfather · 2021-12-17 06:38 Quote from: winni on December 16, 2021, 08:53:10 pmHi! This can be done with only the system functions: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var err : integer;     i,k : Int64;     s : string;   ...   val ('%1',i,err);   val ('$123456789ABCDEF',k,err);   s :=  BinStr(i*k,64);           There are so many powerful functions in the system unit - often the stuff in the multiple units is redundand. Winni Hi Winni, That looks like a really nice solution - I'll definitely give that a go - thanks! ---------------------------------------------------------------------- jollytall · 2021-12-17 07:38 I agree for this simple case there are solutions available in the system. My unit: - can do it in any base 2-16 - can do any length number - and can do arithmetic with it So, as said above, for a simple conversion it is a bit of overkill. @BobDog: Nice to do repeated conversion for long numbers if both are bases 2^n. (What would you like me to check?). @winnin: In your example, you do not need to multiply by 1. I only used it to indicate that the result I want to see in base 2. However that is not necessary in my unit either, if one is willing to use a function: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i s := ConvertNumberToBinString('$123456789ABCDEF0123456789ABCDEF') also works. ---------------------------------------------------------------------- 440bx · 2021-12-17 10:41 Just in case the OP might be interested, here is a HexToBin function from scratch (it should be fast ) and a few test cases for it:Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i {$APPTYPE CONSOLE} program _HexToBin;   function HexToBin(InHex : pchar; OutBin : pchar; InBinSize : ptrint) : boolean;type  THEX_RANGE      = '0'..'F'; const  HexValid        : set of char = ['0'..'9', 'A'..'F'];   BinTable        : array[THEX_RANGE] of pchar =  (   '0000', '0001', '0010', '0011',             {  0..3 }   '0100', '0101', '0110', '0111',             {  4..7 }   '1000', '1001',                           {  8..9 }    { next 7 characters in the ASCII table are not hex digits                  }    #0,     #0,     #0,   #0,     #0,     #0,     #0,    '1010', '1011', '1100', '1101',           {  A..D }   '1110', '1111'                              {  E..F }  );   LOWERCASE_CLEAR  = not (ord('a') - ord('A'));        { should be (not $20)  }   NIBBLES_PER_BYTE = 2;  BITS_PER_NIBBLE  = bitsizeof(byte) div NIBBLES_PER_BYTE; var  HexLen          : ptrint;   c               : char;   Hex             : pchar;                   { to walk the input            }  Bin             : pchar;                   { to set the output            }  begin  result := FALSE;   if InBinSize <= 0 then exit;                 { validate output buffer size  }   OutBin^  := #0;                              { initialize to null           }   HexLen := strlen(InHex);                     { it better be null terminated }   if HexLen <= 0 then exit;   if (HexLen * BITS_PER_NIBBLE) >= InBinSize then exit;    { insufficient     }   Hex := InHex;  Bin := OutBin;   while TRUE do  begin    c := Hex^;     { uppercase the digit if necessary                                      }     if c in ['a'..'f'] then byte(c) := byte(c) and byte(LOWERCASE_CLEAR);     if not (c in HexValid) then break;     { the four bytes that make up a nibble can be seen as a DWORD, move all }    { four of them as a DWORD                                               }     PDWORD(Bin)^ := PDWORD(BinTable[c])^;    inc(Bin, BITS_PER_NIBBLE);          { or sizeof(DWORD), same thing        }   inc(Hex);                           { point to next input hex digit     }     if Hex^ = #0 then  { exit(TRUE); }  { everything went well              }    begin      Bin^   := #0;       result := TRUE;      exit;    end;  end;   { there must have been an invalid hex digit in the input, reset the         }  { output/result to empty                                                  }   OutBin^ := #0;end;   const  TestData     : packed array[0..30] of pchar =  (   '0',  '1',  '2',  '3',  '4',  '5',  '6',  '7',  '8',  '9',  'A',  'B',   'C',  'D',  'E',  'F',    '01', '10', '9a', '9A', 'a9', 'A9', 'f0', 'F0', 'FF', 'ff', 'aa', 'AA',    'F01Abc48',       { result fits exactly in the 32 bytes used as buffer     }    '123ABCZ',        { not a valid hex number                                 }     '012345678'       { bin doesn't fit in the buffer (size 32 + 1)            }  );  var  OutBinBuffer : packed array[0..32] of char;        { 33 bytes             }   i            : ptrint;  begin  writeln;  writeln;   for i := low(TestData) to high(TestData) do  begin    if HexToBin(TestData[i], OutBinBuffer, sizeof(OutBinBuffer)) then    begin      writeln('  hex : ', TestData[i]:8, '   bin : ', OutBinBuffer:32);      continue;    end;     writeln;    writeln('  hex ', TestData[i],            ' is either not a valid hex number or' +            ' the buffer is too small for its binary representation');  end;    writeln;  writeln('  press ENTER/RETURN to end this program');  readln;end.                   ETA: added the missing null termination to the output buffer when the conversion is successful (line 78). ---------------------------------------------------------------------- BobDog · 2021-12-17 16:00 You could do it from scratch using case. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i usessysutils; {$MODE objfpc}{$H+}   function hex2bin(hx:ansistring):ansistring;function TrimLeadingZeros(const S: ansistring): ansistring;var  I, L: Int32;begin  L:= Length(S);  I:= 1;  while (I < L) and (S[I] = '0') do Inc(I);  exit(Copy(S, I));end; varb:ansistring='';n:int32;begin hx:=uppercase(hx);      for n :=1 to length(hx) do      begin            case (char(hx[n])) of           '0':b:=b+'0000';             '1':b:=b+'0001';             '2':b:=b+'0010';             '3':b:=b+'0011';             '4':b:=b+'0100';             '5':b:=b+'0101';             '6':b:=b+'0110';             '7':b:=b+'0111';             '8':b:=b+'1000';             '9':b:=b+'1001';             'A':b:=b+'1010';             'B':b:=b+'1011';             'C':b:=b+'1100';             'D':b:=b+'1101';             'E':b:=b+'1110';             'F':b:=b+'1111';             else             exit('not valid');            end;      end;      exit(TrimLead ingZeros(b));end; beginwriteln(hex2bin('123456789ABCDEF'));writeln('Pr ess return to end . . .');readln;end. But I don't know about speed, although you can do big numbers. ---------------------------------------------------------------------- 440bx · 2021-12-17 16:41 Quote from: BobDog on December 17, 2021, 05:00:27 pmBut I don't know about speed, although you can do big numbers. Your approach definitely has simplicity going for it.  It should be slower because of the string additions but, it shouldn't be noticeable unless the function is called a lot (probably over 100,000 times.) Also, I'm not sure that the leading zeroes should be trimmed.  I think that if the hex input number included leading zeroes then the binary representation should show them as well.  If the programmer doesn't want leading zeroes then, the programmer should trim them in the hex string before sending it to HexToBin. ---------------------------------------------------------------------- Josh · 2021-12-17 19:30 another routine Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const hexs= ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']; var bins:array[0..15] of string =('0000','0001','0010','0011','0100','010 1','0110','0111','1000','1001','1010','1011','1100','1101','1110','111 1'); function quickhex2bin(hx:string):string;var i,v:integer;begin  result:='';   if hx='' then exit;  hx:=upcase(hx);  for i:=1 to length(hx) do  begin    if hx[i] in hexs then    begin      val('$'+hx[i],v);      result:=result+bins[v];    end    else result:=result+'ERRR';  end;end; ---------------------------------------------------------------------- winni · 2021-12-17 20:01 Hi! Toto - we're not in Kansas anymore. We are in Pascal: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const hexs=['0'..'9','A'..'F'];  Winni ---------------------------------------------------------------------- Josh · 2021-12-18 02:01 Hi Wini, updated for speed on my dual core laptop 10 million 64bit hexes just under 10secs Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const hexs=['0'..'9','A'..'F'];      hexsl=['0'..'9','a'..'f'];      // avoid using upcase 2 sets required      bins:array[0..15] of string =('0000','0001','0010','0011','0100','0101','0110','0111',                               '1000','1001','1010','1011','1100','1101','1110','1111');  function quickhex2bin(hx:String):String;var i:int16;    v:byte; function quickhextobyte(const x:byte):byte; inline;    // for uppercase setbegin  if x>64 then result:=x-55 else result:=x-48;end; function quickhextobytel(const x:byte):byte; inline;  // for lowercase setbegin  if x>96 then result:=x-87 else result:=x-48;end; begin  result:='';  if hx='' then exit;  for i:=1 to length(hx) do  begin    if hx[i] in hexs then result:=result+bins[quickhextobyte(byte(hx[i]))]  // uppercase hex      else if hx[i] in hexsl then result:=result+bins[quickhextobytel(byte(hx[i]))]   // lowercase hex to avoid using upcase        else result:=result+'ERRR';  end;end;   the code could be improved for speed by setting the length of result to 4*length of hx, then moving the bins element to correct location in result; this would negate the concatenation of result in each iteration of loop; but left as is for ease of reading ---------------------------------------------------------------------- Bart · 2021-12-18 13:42 Quote from: josh on December 18, 2021, 03:01:03 amCode: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const hexs=['0'..'9','A'..'F'];      hexsl=['0'..'9','a'..'f'];      // avoid using upcase 2 sets required...  Hmm... Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const hexs=['0'..'9','A'..'F', 'a'..'f''];  // no upcase required, no 2 sets required.      ...  Bart ---------------------------------------------------------------------- Josh · 2021-12-18 14:35 Hi Bart moded routines. Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i const hexs=['0'..'9','A'..'F','a'..'f'];      bins:array[0..15] of string =( '0000','0001','0010','0011','0100','0101','0110','0111','1000','1001', '1010','1011','1100','1101','1110','1111'); function QuickHex2Bin(hx:String):String;var i:int16;   function QuickHexToValue(const x:byte):byte; inline;  begin    if x<58 then result:=x-48 else if x<71 then result:=x-55 else if x<103 then result:=x-87;  end; begin  result:='';  if hx='' then exit;  for i:=1 to length(hx) do if hx[i] in hexs then result:=result+bins[QuickHexToValue(byte(hx[i]))] else result:=result+'ERRR';end; ---------------------------------------------------------------------- 440bx · 2021-12-18 14:46 Hi Josh, My concern with your algorithm is that it needs a lot of "magic" numbers to correctly map a character's ordinal to a correct index in the bins table. From a performance viewpoint, some characters will require 3 comparisons to calculate the correct index and, as you already know, the string concatenation is expensive but, at least it is logically much clearer than the DWORD "trick" I use. ---------------------------------------------------------------------- 440bx · 2021-12-18 14:55 Quote from: jamie on December 18, 2021, 03:48:12 pmwhat's this, battle of wits ?  No, it's a battle of bits! Welcome to the bit race ---------------------------------------------------------------------- Josh · 2021-12-18 15:17 Hi 440bx, Aim was to use as few string routines to increase performance; and make hopefully readable; i could add the setlength and move to make it a lot faster; but its  not so readable.. comparisons done in probable order ie 0..9 first; then A-F then a-f; could also add constants to make more readible ie Code: [Select]const Ascii_Upper_F=71;Ascii_Lower_f=103;Ascii_9=58;  // all + 1 to allow just a < comparison       Deduct_Ascii_Upper_F=55;Deduct_Ascii_Lower_f=87;Deduct_Ascii_9=48; function QuickHexToValue(const x:byte):byte; inline;   begin     if x 0 do    begin    dec(n);      result[n] := chr(d mod 2 + 48);      d := d div 2;    end;  result := copy(result, n, 65 - n);end; function hex2dec(const h: string): longword;var  b: byte;  i: word;begin  result := 0;  for i := 1 to length(h) do    begin      b := ord(h[i]);      case b of        97..102:          { a..f = 10..15}          b := b - 87;        65..70:            { A..F = 10..15 }          b := b - 55;        48..57:          b := b - 48;      end;      result := result * 16 + b;    end;end; function hex2bin(h: string): string;begin  result := dec2bin(hex2dec(h));end;  begin  //writeln(hex2dec('3b7'));  //writeln(dec2bin(951));  writeln(hex2bin('3b7'));end. ---------------------------------------------------------------------- engkin · 2021-12-19 12:13 Needed a break from what I was working on. Here is the result: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function H2B(const h:string):string;const  bins:array[$0..$F] of string =('0000 ','0001','0010','0011','0100','0101','0110','0111','1000','1001','1010 ','1011','1100','1101','1110','1111'); type  TNibbles=bitpacked record    case boolean of      False:(c:char);      True: (L:$0..$F; H:$0..$F)  end; var  b:PDWord;  n:TNibbles;  i:Integer;begin  SetLength(Result,Length(h) shl 2);  b:=@Result[1];  for i:=1 to Length(h) do  begin    n.c:=h[i];    case n.H of      3:  begin if n.L < 10      then Move(bins[0+n.L][1],b^,4) else exit('Error') end;      4,6:begin if n.L in [1..6] then Move(bins[9+n.L][1],b^,4) else exit('Error') end;      else;        Exit('Error');    end;    inc(b);  end;end; ---------------------------------------------------------------------- engkin · 2021-12-19 18:40 @jamie, looks nice, but it doesn't seem to produce binary string. ---------------------------------------------------------------------- Kays · 2021-12-19 19:56 Quote from: jamie on December 19, 2021, 08:08:06 pm[…] One item I can't remember is the clause used to inform the compiler registers […]ThisCode: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i end ['rax', 'rcx']; is only necessary for certain registers in pure assembly routines like yours. And if you’re already writing assembly, you definitely want to process (at least) eight Bytes, eight chars at once, because the compiler generated code using Pascal source code definitely beats your implementation. ---------------------------------------------------------------------- engkin · 2021-12-19 20:17 Jamie, your code does not give "binary string". It does not, for instance, produce '1110' when given 'E' Your code is Hex String to Decimal, or did I miss something? ---------------------------------------------------------------------- 440bx · 2021-12-19 20:29 Quote from: jamie on December 19, 2021, 09:23:41 pmI don't understand here. The idea was to take a HEX string of chars and generate a binary of it. a binary string, i.e, a string of '0's and '1's - not the binary number represented by a hex string. ---------------------------------------------------------------------- Seenkao · 2021-12-20 02:44 Quote from: engkin on December 19, 2021, 01:13:41 pmNeeded a break from what I was working on. Here is the result: Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i function H2B(const h:string):string;const  bins:array[$0..$F] of string =('0000 ','0001','0010','0011','0100','0101','0110','0111','1000','1001','1010 ','1011','1100','1101','1110','1111'); type  TNibbles=bitpacked record    case boolean of      False:(c:char);      True: (L:$0..$F; H:$0..$F)  end; var  b:PDWord;  n:TNibbles;  i:Integer;begin  SetLength(Result,Length(h) shl 2);  b:=@Result[1];  for i:=1 to Length(h) do  begin    n.c:=h[i];    case n.H of      3:  begin if n.L < 10      then Move(bins[0+n.L][1],b^,4) else exit('Error') end;      4,6:begin if n.L in [1..6] then Move(bins[9+n.L][1],b^,4) else exit('Error') end;      else;        Exit('Error');    end;    inc(b);  end;end;Можно немного проще Eng: Can be a little simpler  Code: Pascal  [Select][+][-]window.onload = function(){var x1 = document.getElementById("main_content_section"); if (x1) { var x = document.getElementsByClassName("geshi");for (var i = 0; i var  bb: integer;  ...for i := 1 to Length(h) do  begin    bb := Byte(h[i]);  case bb of        48..57: Result := Result + bins[bb - 48];        65..70: Result := Result + bins[bb - 55];        97..102: Result := Result + bins[bb - 87];      else begin        Result := 'Error';      exit;      end;    end;  end;       Иногда простые вещи могут быть более эффективными и понятными. Но ваше решение мне понравилось! Eng: Sometimes simple things can be more effective and understandable. But I liked your decision! ---------------------------------------------------------------------- engkin · 2021-12-20 03:53 Yes, definitely.