您当前的位置: 首页 > 

寒冰屋

暂无认证

  • 0浏览

    0关注

    2286博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

定点数转换器

寒冰屋 发布时间:2020-04-11 16:06:25 ,浏览量:0

目录

介绍

背景

使用代码

介绍

音频处理器通常使用定点数字表示音频信号。在开发用于连接到音频处理器的GUI的过程中,我需要一种简单的方法来向用户显示定点编号。这个简单的类是一个定点数容器,它允许将值读取或写入为定点值或double。

背景

定点数历史悠久,尤其是在浮点模块可用于CPU之前。DSP通常会使用固定数字格式,因为它们通常没有浮点模块。

音频DSP以定点数字格式表示音频信号。“1.31”的音频格式有一个数字范围或者-1...... +1。在我的特定例子中,我需要使用数字范围为-8... +8 的“4.20”格式。“4.20”格式将具有1个符号位,3个十进制位和20个小数位。

使用代码

FixedPoint类介绍如下:

/// 
/// A class to convert fixed point numbers from/to doubles.
/// 
public class FixedPoint
{
    private readonly int _fracWidth;
    private readonly int _decWidth;
    private readonly int _fracMask;
    private readonly int _decMask;
    private readonly int _signMask;
    private readonly int _fullMask;
    private readonly double _minValue;
    private readonly double _maxValue;

    #region Properties
    private readonly bool _error;
    public bool Error
    {
        get { return _error; }
    }

    /// 
    /// Is value negative
    /// 
    public bool IsNegative
    {
        get { return (ValueAsFixedPoint & _signMask) != 0; }
    }

    /// 
    /// Get decimal part of fixed number
    /// 
    public int GetDecimal
    {
        get { return (ValueAsFixedPoint >> _fracWidth) & _decMask; }
    }

    /// 
    /// Get fraction part of fixed point number
    /// 
    public int GetFraction
    {
        get { return ValueAsFixedPoint & _fracMask; }
    }

    private int _val;
    /// 
    /// Get/Set value with fixed point number
    /// 
    public int ValueAsFixedPoint
    {
        get { return _val; }
        set { _val = value & _fullMask; }
    }

    /// 
    /// Get/Set value with double
    /// 
    public double ValueAsDouble
    {
        get { return ConvertToDouble(_val); }
        set { _val = ConvertToFixedPoint(value); }
    }
    #endregion

    /// 
    /// Instantiate a fixed point number
    /// 
    /// fixed point number format
    public FixedPoint(string format)
    {
        // extract pieces from the format definition
        var s = format.Split(new char[] { '.' });
        if (s.Length != 2) { _error = true; return; }
        var b = int.TryParse(s[0], out _decWidth);
        if (!b) { _error = true; return; }
        b = int.TryParse(s[1], out _fracWidth);
        if (!b) { _error = true; return; }

        // calculate values to be used later
        for (var i = 0; i < _fracWidth; ++i) _fracMask = (_fracMask             
关注
打赏
1665926880
查看更多评论
0.0468s