Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在C+中将二进制文件中的小尾数读入整数+;_C++_File_Wav_Endianness - Fatal编程技术网

C++ 在C+中将二进制文件中的小尾数读入整数+;

C++ 在C+中将二进制文件中的小尾数读入整数+;,c++,file,wav,endianness,C++,File,Wav,Endianness,我正在解析一个wav文件,并通过给定的因子使其减速或加速。所以我想从wave文件头读取采样率和字节率,并根据因子修改它。问题是他们在小恩迪亚 在C中,我可以做到这一点 inline void endian_swap(unsigned int& x) { x = (x>>24) | ((x<<8) & 0x00FF0000) | ((x>>8) & 0x0000FF

我正在解析一个wav文件,并通过给定的因子使其减速或加速。所以我想从wave文件头读取采样率和字节率,并根据因子修改它。问题是他们在小恩迪亚

在C中,我可以做到这一点

inline void endian_swap(unsigned int& x)
    {
        x = (x>>24) | 
            ((x<<8) & 0x00FF0000) |
            ((x>>8) & 0x0000FF00) |
            (x<<24);
    } 
<>但是我怎么能在C++中做同样的事情呢? 我试过了

    int length = 4; 
    my_input_file.read(&num, length);
但它不起作用,因为编译器希望在第一个参数中有一个char指针。我在代码中的任何地方都在使用文件流,这就是为什么我不能只使用文件指针而用C的方式来完成它。你知道我该怎么做吗

此外,我是否可以使用sscanf将二进制文件中的小endian格式数据直接读取为整数

在C中,我可以做到这一点

inline void endian_swap(unsigned int& x)
    {
        x = (x>>24) | 
            ((x<<8) & 0x00FF0000) |
            ((x>>8) & 0x0000FF00) |
            (x<<24);
    } 
您的方法存在以下问题:

  • 它只在字节有8位时工作。这不是C语言(或C++语言)所能保证的
  • 仅当
    usigned int
    有4个字节时,它才起作用。这不是C(或C++)标准的保证
  • 如果CPU本机是大端输入,则只应对小端输入进行交换。这不是C(或C++)标准的保证。请注意,x86是little endian
  • C没有引用
  • <如何在C++中实现同样的操作?< /P>

    除了上述问题, EndiaNoSuff碰巧是有效的C++。< /P> 在C++中,可以使用这个方法将二进制文件读入内存:

    std::ifstream is(filename, std::ios::in | std::ios::binary);
    std::istreambuf_iterator<char> begin = is;
    std::istreambuf_iterator<char> end = {};
    std::vector<unsigned char> data(begin, end);
    
    std::ifstream是(文件名,std::ios::in | std::ios::binary);
    std::istreambuf_迭代器begin=is;
    std::istreambuf_迭代器end={};
    std::矢量数据(开始、结束);
    
    @Timo:用于读取二进制文件?
    length=sizeof(int);my_input_file.read(reinterpret_cast(&num),长度)
    @tedlynmo:最好使用
    std::int32\t
    ,因为二进制格式不依赖于目标
    int
    size;)op>读入一个
    uint8\u t字节[4]
    然后将结果计算为
    bytes[0]+(bytes[1],在C中,您不能这样做
    内联无效端交换(unsigned int&x)