|  |  | - with POV-Ray scene description language.
See this thread "Re: binary help" (5. Oct. this group)
news://news.povray.org/3BCB3A33.1E311C94%40hotmail.com
I found this problem quite interesting,
so I just couldn't leave it alone.
Hopefully the tests at the end of my code
have scared out all the bugs   ;)
Note about the dec2bin() macro:
In my copy of v3.5.beta.4.msvc.win32,
values for the Ndigits parameter greater
than 31 generates wrong results.
Tor Olav
// ===== 1 ======= 2 ======= 3 ======= 4 ======= 5 ======= 6 ======= 7 =
// Copyright 2001 by Tor Olav Kristensen
// mailto:tor### [at] hotmail com
// http://www.crosswinds.net/~tok
// ===== 1 ======= 2 ======= 3 ======= 4 ======= 5 ======= 6 ======= 7 =
#version 3.5;
// ===== 1 ======= 2 ======= 3 ======= 4 ======= 5 ======= 6 ======= 7 =
#declare log2 = function(N) { ln(N)/ln(2) }
#macro Sign(Num)
  #if (Num = 0)
    #local S = ""
  #else
    #if (Num > 0)
      #local S = "+"
    #else
      #local S = "-"
    #end // if
  #end // if
  S
#end // macro Sign
#macro d2b(Num, NrOfDigits)
  #local N = Num;
  #local S = ""
  #local Cnt = 0;
  #while (Cnt < NrOfDigits)
    #if (mod(N, 2) = 0)
      #local S = concat("0", S)
    #else
      #local S = concat("1", S)
    #end // if
    #local N = div(N, 2);
    #local Cnt = Cnt + 1;
  #end // while
  S
#end // macro d2b
#macro dec2bin(N, Ndigits)
  #local Nabs = abs(N);
  #if (N = 0)
    #local E = 0;
    #local Exponent = "0"
  #else
    #local E = floor(log2(Nabs));
    #local Eabs = abs(E);
    #if (E = 0)
      #local Edigits = 1;
    #else
      #local Edigits = 1 + floor(log2(Eabs));
    #end // if
    #local Exponent = d2b(Eabs, Edigits)
  #end // if
  #local Mabs = int(Nabs*2^(Ndigits - E - 1));
  #local Mantissa = d2b(Mabs, Ndigits)
  #if (Ndigits >= 2)
    #local Mantissa = concat(
                        substr(Mantissa, 1, 1),
                        ".",
                        substr(Mantissa, 2, Ndigits - 1)
                      )
  #end // if
  concat(Sign(N), Mantissa, "E", Sign(E), Exponent)
#end // macro dec2bin
// ===== 1 ======= 2 ======= 3 ======= 4 ======= 5 ======= 6 ======= 7 =
#macro Test(NN, Digits)
  #debug "\n"
  #debug str(NN, 0, -1)
  #debug " = "
  #debug dec2bin(NN, Digits)
#end // macro Test
Test(0, 8)            // 0.0000000E0
Test(0.000471, 16)    // +1.111011011110000E-1100
Test(-33.333333, 16)  // -1.000010101010101E+101
Test(1024.5, 14)      // +1.0000000000100E+1010
Test(2^-16, 6)        // +1.00000E-10000
Test(2^128, 12)       // +1.00000000000E+10000000
Test(1, 4)            // +1.000E0
Test(-2, 4)           // -1.000E+1
Test(0.7, 16)         // +1.011001100110011E-1
Test(-34.578E-10, 31) // -1.110110110011110010000101100101E-11101
#debug "\n\n"
// ===== 1 ======= 2 ======= 3 ======= 4 ======= 5 ======= 6 ======= 7 = Post a reply to this message
 |  |