优化代码以读取文件中的某些 VLV?
Optimizing code for reading some VLVs in a file?
我正在尝试从我创建的文件中读取一些 variable-length-values。
文件包含以下内容:
81 7F 81 01 2F F3 FF
那里有两个 VLV,81 7F
和 81 01
,它们是十进制的 255
和 129
。
我还创建了一些文件-reader 函数,如下所示:
void read_byte_from_file_to(std::fstream& file, uint8_t& to) {
file.read((char*)&to, 1);
}
unsigned long readVLV(std::fstream& t_midi_file) {
unsigned long result = 0;
static unsigned long sum = 0, depth = 0, count = 0;
uint8_t c;
read_byte_from_file_to(t_midi_file, c);
++count;
if (c & 0x80) {
readVLV(t_midi_file);
}
sum += (c & 0x7F) << (7 * depth++);
if (count == depth) {
result = sum;
sum = 0;
depth = 0;
count = 0;
}
return result;
};
虽然 运行 readVLV
n
次在从文件读取时给出前 n
VLV 的正确答案,但我绝对讨厌我的写法,所以许多静态参数和丑陋的参数重置。所以,如果有人能引导我朝着正确的方向前进,我将非常高兴。
获取函数位置状态的基本_readVLV
可以通过编写
来完成
unsigned long _readVLV(
std::fstream& t_midi_file,
unsigned long sum,
unsigned long depth) {
uint8_t c;
read_byte_from_file_to(t_midi_file, c);
if (c & 0x80) {
sum += _readVLV(t_midi_file, sum, depth);
++depth;
}
return (c & 0x7F) << (7 * depth);
}
并创建一个全局 readVLV
函数来获取位置信息和文件,就像这样
unsigned long readVLV(std::fstream& t_midi_file) {
unsigned long sum = 0, depth = 0, count = 0;
return _readVLV(t_midi_file, sum, depth, count);
}
我正在尝试从我创建的文件中读取一些 variable-length-values。
文件包含以下内容:
81 7F 81 01 2F F3 FF
那里有两个 VLV,81 7F
和 81 01
,它们是十进制的 255
和 129
。
我还创建了一些文件-reader 函数,如下所示:
void read_byte_from_file_to(std::fstream& file, uint8_t& to) {
file.read((char*)&to, 1);
}
unsigned long readVLV(std::fstream& t_midi_file) {
unsigned long result = 0;
static unsigned long sum = 0, depth = 0, count = 0;
uint8_t c;
read_byte_from_file_to(t_midi_file, c);
++count;
if (c & 0x80) {
readVLV(t_midi_file);
}
sum += (c & 0x7F) << (7 * depth++);
if (count == depth) {
result = sum;
sum = 0;
depth = 0;
count = 0;
}
return result;
};
虽然 运行 readVLV
n
次在从文件读取时给出前 n
VLV 的正确答案,但我绝对讨厌我的写法,所以许多静态参数和丑陋的参数重置。所以,如果有人能引导我朝着正确的方向前进,我将非常高兴。
获取函数位置状态的基本_readVLV
可以通过编写
unsigned long _readVLV(
std::fstream& t_midi_file,
unsigned long sum,
unsigned long depth) {
uint8_t c;
read_byte_from_file_to(t_midi_file, c);
if (c & 0x80) {
sum += _readVLV(t_midi_file, sum, depth);
++depth;
}
return (c & 0x7F) << (7 * depth);
}
并创建一个全局 readVLV
函数来获取位置信息和文件,就像这样
unsigned long readVLV(std::fstream& t_midi_file) {
unsigned long sum = 0, depth = 0, count = 0;
return _readVLV(t_midi_file, sum, depth, count);
}