Read OpenCV FOURCC code int to char conversion

948 Views Asked by At

I got the following code to read the FOURCC code of a video file:

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;

This code outputs %c%c%c%c and it should output HDYC. If I modify the code to

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;

I get as output:

CAP_PROP_FOURCC: 48445943

I tried changing the fmt type to :x and I got an exception.

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;

This code works as I expected and prints the FOURCC code '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

How do I use fmt with the correct syntax to get the FOUCC HDYC?

1

There are 1 best solutions below

0
On

The c specifier works with int and {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);
}

Output:

HDYC