简体   繁体   English

将uint8_t数据与字符串进行比较

[英]Comparing uint8_t data with string

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). 这可能听起来有点奇怪或问题可能是微不足道的,但在我生命的大部分时间里,我用PHP编程(是的,我知道它听起来如何)。 So when I switched to C++ there are things quite unfamilliar for me (cause of php habits). 因此,当我切换到C ++时,有些事情对我来说非常不合适(导致php习惯)。

So I'm loading wav header data using struct. 所以我使用struct加载wav头数据。 Values are definded as uint8_t type: 值定义为uint8_t类型:

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 }

This should be easy check if loaded file is a Wave file (*.wav). 如果加载的文件是Wave文件(* .wav),应该很容易检查。 Thanks for any help. 谢谢你的帮助。

Strings in C and C++ are null-terminated . C和C ++中的字符串以空值终止 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 . RIFFWAVE在技​​术上不是C风格的字符串,因为没有空终止符,所以你不能只使用简单的C / C ++风格的字符串比较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) { // .. }

I would personally use either strncmp or memcmp . 我个人会使用strncmpmemcmp They end up doing the same thing, but semantically strncmp is a string compare function which maybe makes the code clearer. 他们最终做同样的事情,但语义strncmp是一个字符串比较函数,可能使代码更清晰。

For strncmp see here . 对于strncmp请看这里 For memcmp see here . 对于memcmp请看这里

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

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