Frage

Ich lese ein binäres Datenformat mit Chicken und habe bisher Intts zum Arbeiten gebracht, indem ich Dinge wie (fx+ (fxshl (read-byte) 8) (read-byte)) (Big Endian) gemacht habe.

Wie kann ich Floats lesen und schreiben?Ich muss in der Lage sein, IEEE 754-2008 32-Bit- und 64-Bit-Binär-Floats zu lesen und zu schreiben.

War es hilfreich?

Lösung

Ich habe bisher keine guten Bibliotheken dafür gefunden, aber ich habe etwas zusammen gehackt, das funktioniert.Beachten Sie, dass mir nur read-byte und read-string als Eingabeoperationen zur Verfügung stehen.

  ;;
  ;; These are some unfun C routines to convert 4 int-promoted bytes to a float
  ;; by manually assembling the float using bitwise operators
  ;;
  ;; Caveat! These will only work on platforms in which floats are 32-bit Big
  ;; Endian IEEE754-2008 numbers and doubles are 64-bit Big Endian IEEE754-2008
  ;; numbers! Also, stdint.h.
  ;;
  (define (readFloat)
    (let ([c-read-float
            (foreign-lambda* float
              ((int i1)
               (int i2)
               (int i3)
               (int i4))
               "uint8_t b1 = (uint8_t) i1;
                uint8_t b2 = (uint8_t) i2;
                uint8_t b3 = (uint8_t) i3;
                uint8_t b4 = (uint8_t) i4;

                uint32_t i = 0;

                i = b1;
                i = (i << 8) | b2;
                i = (i << 8) | b3;
                i = (i << 8) | b4;

                float f = *(float*)&i;

                C_return(f);")])
        (let* ([i1 (read-byte)]
               [i2 (read-byte)]
               [i3 (read-byte)]
               [i4 (read-byte)])
          (c-read-float i1 i2 i3 i4))))

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top