Converting Integer number into hexadecimal number in delphi 7 -


write program convert integer number hexadecimal representation without using inbuilt functions.

here code, not working. can tell mistake?

it giving error:

"project raised exception class eaccessviolation message 'access violation @ address 00453b7b in module 'project.exe'.write of address ffffffff'.process stopped.use step or run continue."

unit unit1;  interface  uses       windows, messages, sysutils, variants, classes, graphics,     controls,forms,   dialogs;  type   tform1 = class(tform)   end; function hexvalue(num:integer):char;  var   form1: tform1;  implementation  {$r *.dfm} function hexvalue(num:integer):char;   begin     case num of       10: result:='a';       11: result:='b';       12: result:='c';       13: result:='d';       14: result:='e';       15: result:='f';     else result:=chr(num);   end; end;  var   intnumber,hexnumber,actualhex:string;   integernum:integer;   i,j,k:byte;  begin   inputquery ('integer number','enter integer number', intnumber);   integernum:=strtoint(intnumber);   i:=0;   while integernum >= 16     begin       hexnumber[i]:=hexvalue(integernum mod 16);       integernum:= integernum div 16;       inc(i);     end;   hexnumber[i]:= hexvalue(integernum);   k:=i;   j:=0 k      begin       actualhex[j]:= hexnumber[i];       dec(i);     end;   showmessage(actualhex);  end. 

first mistake : string 1 indexed. meaning index of first character 1 , not 0. initialize "i" 0 , try set hexnumber[i].

second mistake : strings might dynamic, don't grow automatically. if try access first character of empty string, won't work. need call setlength(hexnumber, numberofdigits). can calculate number of digits way :

numberofdigits := trunc(log16(integernum)) + 1; 

since log16 isn't exists, can either use logn(16,integernum) or (log(integernum) / log(16)) depending on available in version of delphi.

note might return invalid value very, large value (high int64 range) due rounding errors.

if don't want go road, replace instruction by

hexnumber := hexvalue(integernum mod 16) + hexnumber; 

which remove need invert string @ end.

third mistake : using unsigned integer loop variable. while debatable, instruction

for := 0 count - 1 

is common practice in delphi without checking count > 0. when count = 0 , using unsigned loop counter, you'll either integer overflow (if have them activated in project options) or you'll loop high(i) times, isn't want doing.

fourth mistake : mentionned : result:=chr(num) should replaced result := inttostr(num)[1]. personally, i'd implement function using array.

hexarr : array[0..15] of char = ('0', '1',...,'d','e','f'); begin   if inrange(num, 0, 15)     result := hexarr[num]   else     //whatever want end; 

Comments

Popular posts from this blog

PHP DOM loadHTML() method unusual warning -

python - How to create jsonb index using GIN on SQLAlchemy? -

c# - TransactionScope not rolling back although no complete() is called -