代码之家  ›  专栏  ›  技术社区  ›  fearless_fool

如何将python列表格式化为初始化的C数组?

  •  0
  • fearless_fool  · 技术社区  · 6 年前

    我需要为用C编写的嵌入式固件生成一个查找表。用python生成值很容易,但是如何以C编译器接受的格式输出这些值呢?

    例如,我想要这样的东西:

    >>> a = range(0,20)
    >>> print(to_c_array(a))
    int table[] = {
        0, 1, 2, 3, 4, 5, 6, 7,
        8, 9, 10, 11, 12, 13, 14, 15,
        16, 17, 18, 19};
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   fearless_fool    6 年前

    这里有一个功能可以满足您的要求:

    def to_c_array(values, ctype="float", name="table", formatter=str, colcount=8):
        # apply formatting to each element
        values = [formatter(v) for v in values]
    
        # split into rows with up to `colcount` elements per row
        rows = [values[i:i+colcount] for i in range(0, len(values), colcount)]
    
        # separate elements with commas, separate rows with newlines
        body = ',\n    '.join([', '.join(r) for r in rows])
    
        # assemble components into the complete string
        return '{} {}[] = {{\n    {}}};'.format(ctype, name, body)
    

    …以及如何使用它生成伽玛校正的示例 查找表:

    >>> gamma = 0.3
    >>> N = 32
    >>> values = [math.pow(float(i)/N, gamma) for i in range(N)]
    >>> print(to_c_array(values, ctype='float', name='gamma', formatter=lambda x: '{:0.5f}'.format(x)))
    float gamma[] = {
        0.00000, 0.35355, 0.43528, 0.49158, 0.53589, 0.57299, 0.60520, 0.63385,
        0.65975, 0.68348, 0.70543, 0.72589, 0.74509, 0.76320, 0.78036, 0.79668,
        0.81225, 0.82716, 0.84147, 0.85523, 0.86849, 0.88129, 0.89368, 0.90568,
        0.91731, 0.92862, 0.93961, 0.95031, 0.96073, 0.97090, 0.98082, 0.99052};