本文介绍了将 uint8_t 数据与字符串进行比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这听起来可能有点奇怪,或者问题可能是微不足道的,但在我生命的大部分时间里,我都在用 PHP 编程(是的,我知道这听起来如何).所以当我切换到 C++ 时,对我来说有些陌生(因为 php 习惯).

This may sounds little odd or question may be a trivial one, but for most of my life I was programming in PHP (yeah, I know how it sounds). So when I switched to C++ there are things quite unfamilliar for me (cause of php habits).

所以我正在使用结构加载 wav 标头数据.值定义为 uint8_t 类型:

So I'm loading wav header data using struct. Values are definded as uint8_t type:

typedef struct  WAV_HEADER
{
   uint8_t         RIFF[4];        // RIFF
   uint8_t         WAVE[4];        // WAVE
}

我必须将它们与四字母字符串进行比较:

I have to compare them with four-letter strings for something like that:

if(wavHeader.RIFF[0] . wavHeader.RIFF[1] . wavHeader.RIFF[2] . wavHeader.RIFF[3] == 'RIFF')
{ do sth }

如果加载的文件是 Wave 文件 (*.wav),这应该很容易检查.感谢您的帮助.

This should be easy check if loaded file is a Wave file (*.wav). Thanks for any help.

推荐答案

C 和 C++ 中的字符串是 以空字符结尾.RIFFWAVE 在技术上不是 C 风格的字符串,因为没有空终止符,所以你不能像 strcmp.但是,您可以通过多种方式将它们与您想要的字符串进行比较:

Strings in C and C++ are null-terminated. RIFF and WAVE aren't technically C-style strings because there is no null terminator, so you can't just use a straightforward C/C++-style string compare like strcmp. There are however several ways you could compare them against the strings you want:

  • if (header.RIFF[0] == 'R' &&header.RIFF[1] == 'I' &&header.RIFF[2] == 'F' &&header.RIFF[3] == 'F') {//.. }
  • if (strncmp((const char*)header.RIFF, "RIFF", 4) == 0) {//.. }
  • if (memcmp(header.RIFF, "RIFF", 4) == 0) {//.. }

我个人会使用 strncmpmemcmp.他们最终做了同样的事情,但语义上strncmp是一个字符串比较函数,它可能会使代码更清晰.

I would personally use either strncmp or memcmp. They end up doing the same thing, but semantically strncmp is a string compare function which maybe makes the code clearer.

对于strncmp,请参见此处.对于 memcmp,请参见此处.

For strncmp see here.For memcmp see here.

这篇关于将 uint8_t 数据与字符串进行比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-16 17:48