简体   繁体   English

带舍入的C ++函数(跨平台)

[英]C++ function with rounding (cross-platform)

I have the following function that I just can't get right. 我有以下我无法正确实现的功能。 I am working on it again and again, and somehow something always turns out wrong. 我一遍又一遍地研究它,以某种方式总是发现错误。

I have encoded some audio data. 我已经编码了一些音频数据。 The audio data is encoded in "frames" of 3 bytes each. 音频数据被编码为每个3字节的“帧”。

For example like this: 例如这样:

Frame #1
0
1
2

Frame #2
3
4
5

Frame #3
6
7
8

Now when I want to decode some audio (let's say from byte position 4 with the length of 3 bytes, I first have to calculate in which frame this audio would be found and how many frames I have to decode and what the offset in the decoded frame is. 现在,当我想解码一些音频时(例如,从3字节长度的字节位置4开始),我首先必须计算将在哪个帧中找到该音频,以及我必须解码多少帧,以及解码后的偏移量是多少。框架是。

In this case, I would have to read frame #2 and #3, and the offset would be 1. 在这种情况下,我将不得不读取第2帧和第3帧,并且偏移量将为1。

I have tried to set up the following void: 我尝试设置以下空白:

int g_iByteSize1FrameDecoded = 3;

void CalcFrames(unsigned long uByteStart,unsigned long uByteCount,unsigned long &uStartFrame,unsigned long &uFramesToRead,unsigned long& uOffset)
{
    ////calculate in which decoded frame the byte from uByteStart would be found in
    uStartFrame = ((uByteStart) / g_iByteSize1FrameDecoded) + 1;
    unsigned long iEndFrame = ((uByteStart + uByteCount) / g_iByteSize1FrameDecoded) + 1;

    uFramesToRead = (iEndFrame - uStartFrame + 1);

    uOffset = (uByteStart) % g_iByteSize1FrameDecoded;
}

But it just doesn't work, something ALWAYS goes wrong... rounding, the math itself... 但这只是行不通,总会出错...四舍五入,数学本身...

Could somebody with some math skills perhaps have a look where my error(s) could be? 可能会有一些数学技能的人看看我的错误可能在哪里吗?

Byte i is in frame i / 3 at offset i % 3: 字节i在帧i / 3中在偏移i%3处:

void CalcFrames(unsigned long uByteStart,unsigned long uByteCount,unsigned long &uStartFrame,unsigned long &uFramesToRead,unsigned long& uOffset) {
    uStartFrame = uByteStart / g_iByteSize1FrameDecoded + 1;
    uOffset = uByteStart % g_iByteSize1FrameDecoded;
    unsigned long lastFrame = (uByteStart + uByteCount - 1) / g_iByteSize1FrameDecoded + 1;
    uFramesToRead = lastFrame - uStartFrame + 1;
}

I'm dubious about your decision to count frames and bytes starting from 1 rather than 0, but perhaps it works better for the rest of your code - I don't know. 我对您决定从1开始而不是从0开始计数帧和字节的决定表示怀疑,但是对于您的其余代码来说,它可能更有效-我不知道。

As far as CalcFrames goes, I can only see an issue with uOffset . CalcFrames而言,我只能看到uOffset的问题。 The calculation should be: 计算应为:

uOffset = (uByteStart % g_iByteSize1FrameDecoded) - 1;

For your example, the offset of byte 5 from the start of the frame is 1 byte. 对于您的示例,字节5从帧开始的偏移量是1个字节。 Your original calculation simply does 5 % 3 which is 2, hence the need to additionally subtract 1. 您的原始计算只做5%3,即2,因此需要另外减去1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM