Comparing uint8_t data with string

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-20 03:55:12

问题


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).

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 }

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


回答1:


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) { // .. }

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.

For strncmp see here. For memcmp see here.



来源:https://stackoverflow.com/questions/34693203/comparing-uint8-t-data-with-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!