Set a FourCC value in C++

Nick picture Nick · May 1, 2009 · Viewed 8.1k times · Source

I want to set a FourCC value in C++, i.e. an unsigned 4 byte integer.

I suppose the obvious way is a #define, e.g.

#define FOURCC(a,b,c,d) ( (uint32) (((d)<<24) | ((c)<<16) | ((b)<<8) | (a)) )

and then:

uint32 id( FOURCC('b','l','a','h') );

What is the most elegant way you can think to do this?

Answer

James Hopkin picture James Hopkin · May 1, 2009

You can make it a compile-time constant using:

template <int a, int b, int c, int d>
struct FourCC
{
    static const unsigned int value = (((((d << 8) | c) << 8) | b) << 8) | a;
};

unsigned int id(FourCC<'a', 'b', 'c', 'd'>::value);

With a little extra effort, you can make it check at compile time that each number passed in is between 0 and 255.