Converting decimal/integer to binary - how and why it works the way it does?

后端 未结 6 1420
無奈伤痛
無奈伤痛 2020-12-11 10:15

As already asked David in a comment of an answer here, I\'m really interested on how this function works, since I can\'t seem to get the same (correct) values if changing re

6条回答
  •  盖世英雄少女心
    2020-12-11 10:24

    Personally, I'd do it this way:

    function inttobin (p_nb_int: uint64; p_nb_digits: byte=64): string;
    begin
      SetLength(Result, p_nb_digits);
      while p_nb_digits > 0 do
      begin
        if odd(p_nb_int) then
          Result[p_nb_digits] := '1'
        else
          Result[p_nb_digits] := '0';
        p_nb_int := p_nb_int shr 1;
        dec(p_nb_digits);
      end;
    end;
    

提交回复
热议问题