Printing ap_[u]fixpt Types

The Arbitrary Precision Fixed Point Library provides some utilities for printing ap_[u]fixpt types in software, demonstrated below. The to_fixpt_string(base, signedness) function takes an optional base argument which is one of 2, 10, or 16, and defaults to 10, as well as an optional signedness argument which determines if the data should be treated as signed or unsigned. The signedness argument defaults to false for ap_ufixpt, and true for ap_fixpt.

The output stream operator << can be used to put a fixed point number into an output stream as if it were called with the default to_fixpt_string arguments.

The to_double() function can be useful for printing, but it can lose precision over a wide fixed point. It can be used in hardware, but this is expensive, and should be avoided when possible.

#include "hls/ap_fixpt.hpp"
#include <iostream>
#include <stdio.h>

using namespace hls;
    //...
    ap_ufixpt<8, 4> fixed = 12.75;
    ap_fixpt<8, 4> s_fixed("CC");

    // prints: -52 * 2^-4
    // Read -52 * 0.0625 = -3.25
    std::cout << s_fixed << std::endl;

    // prints: 11001100 * 2^-4
    // Read unsigned 11001100 * 2^-4 = 204 * 0.0625
    // = 12.75
    printf("%s\n", fixed.to_fixpt_string(2).c_str());

    // prints: CC * 2^-4
    // Read signed CC * 2^-4 = -52 * 0.0625
    // = -3.25
    std::cout << s_fixed.to_fixpt_string(16, false) << std::endl;

    // prints: -3.25
    printf("%.2f\n", s_fixed.to_double());
Tip:

The SmartHLS Fixed-Point Math Library includes a gdb pretty-printer that simplifies the debugging of applications that use ap_fixpt datatypes. Once the application is stopped under the the gdb prompt, simply source the file as follows:

(gdb) source <SHLS_ROOT_DIR>/smarthls-library/external/math/utils/gdb-pretty-printers/ap_fixed.py

After that you can visualize any ap_[u]fixpt variable using the print (p) command. The pretty-printer will display the Real value, the hexadecimal representation, the word width (W) and the width of the integer part (IW):

(gdb) print x
$2 = 0.49999999906867743 [0xfffffff8] <W:34,IW:1>
For mor information, see Setup SmartHLS GDB pretty-printer site on GitHub.