1

我得到以下代码来读取视频文件的 FOURCC 代码:

fourcc = (int)cap.get(cv::CAP_PROP_FOURCC);
string fourcc_str = fmt::format("%c%c%c%c", fourcc & 255, (fourcc >> 8) & 255, (fourcc >> 16) & 255, (fourcc >> 24) & 255);
std::cout << "CAP_PROP_FOURCC: " << fourcc_str << std::endl;

此代码输出 %c%c%c%c,它应该输出 HDYC。如果我将代码修改为

fourcc = (int)cap.get(cv::CAP_PROP_FOURCC);
string fourcc_str = fmt::format("{:x}{:x}{:x}{:x}", fourcc & 255, (fourcc >> 8) & 255, (fourcc >> 16) & 255, (fourcc >> 24) & 255);
std::cout << "CAP_PROP_FOURCC: " << fourcc_str << std::endl;

我得到输出:

CAP_PROP_FOURCC: 48445943

我尝试将 fmt 类型更改为 :x ,但出现异常。

fourcc = (int)cap.get(cv::CAP_PROP_FOURCC);
string fourcc_str = fmt::format("{:c}{:c}{:c}{:c}", fourcc & 255, (fourcc >> 8) & 255, (fourcc >> 16) & 255, (fourcc >> 24) & 255);
std::cout << "CAP_PROP_FOURCC: " << fourcc_str << std::endl;

此代码按我的预期工作并打印 FOURCC 代码“HDYC”

 fourcc = (int)cap.get(cv::CAP_PROP_FOURCC);
 char c1 = fourcc & 255;
 char c2 = (fourcc >> 8) & 255;
 char c3 = (fourcc >> 16) & 255;
 char c4 = (fourcc >> 24) & 255;        
 std::cout << "CAP_PROP_FOURCC: " << c1 << c2 << c3 << c4 << std::endl;

CAP_PROP_FOURCC: HDYC

如何以正确的语法使用 fmt 来获取 FOUCC HDYC?

4

1 回答 1

1

说明c符与int{fmt} 7+ ( godbolt ) 一起使用:

#include <fmt/core.h>

int main() {
  int fourcc = ('C' << 24) | ('Y' << 16) | ('D' << 8) | 'H';
  std::string fourcc_str = fmt::format(
    "{:c}{:c}{:c}{:c}", fourcc & 255, (fourcc >> 8) & 255,
    (fourcc >> 16) & 255, (fourcc >> 24) & 255);
  fmt::print(fourcc_str);
}

输出:

HDYC
于 2021-06-15T14:47:10.123 回答