1

I knew about the standard 'e' exponent for decimal notation, but the linux man page of strtod says about the hexadecimal notation:

A hexadecimal number consists of a "0x" or "0X" followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent. A binary exponent consists of a 'P' or 'p', followed by an optional plus or minus sign, followed by a nonempty sequence of decimal digits, and indicates multiplication by a power of 2. At least one of radix character and binary exponent must be present.

Playing with a C compiler: 0x0123456789ABCDEFp019 is equal to 4.2984030182685396e+22 but I cannot reimplement that successfully myself.

theor
  • 1,545
  • 1
  • 9
  • 16
  • you could look at the source code for strtod in either glibc or musl? – Daniel Jour Dec 24 '19 at 10:20
  • 1
    A rudimentary implementation could be along these lines: `double d = 0.0; char s[] = "0x0123456789ABCDEFp019"; unsigned long whole; int exponent; if (sscanf(s, "%lx%*[pP]%d", &whole, &exponent) == 2) d = ldexp(whole, exponent);`. The significand part can contain a period (.) and can be negative. You must check (and treat accordingly) all these possibilities too. – Lxer Lx Dec 24 '19 at 12:32
  • What do you mean by "convert to decimal". What's the target type that you're aiming for? `char *`? `double`? Or are you actually targeting something like the `decimal64` decimal floating-point type? – Mark Dickinson Dec 24 '19 at 21:59
  • @DanielJour I have to admit the code of glibc is a bit intense, I was looking for an overview of how it works. The code: https://sourceware.org/git/?p=glibc.git;a=blob_plain;f=stdlib/strtod_l.c;h=9fc9e4c0130f0ae97f29a9b343f18a2599e8ffcf;hb=HEAD – theor Dec 25 '19 at 10:03
  • @MarkDickinson sorry that wasn't clear, I mean converting that to double. This notation is part of the web assembly spec (the reference interpreter is implemented in ocaml, which uses strtod down the line) and I'm implementing an interpreter in c#, so I need to reimplement this notation which is not supported by .net's float.Parse by default. – theor Dec 25 '19 at 10:05
  • @LxerLx Oh well, I feel stupid now. I was trying to reinterpret the part before the `p` as a float when it's a straight ulong. It works: https://dotnetfiddle.net/89Fg7T Thank you – theor Dec 25 '19 at 10:17

0 Answers0