Hatted Rooster
Hatted Rooster

Reputation: 36483

concatenating escape sequence string in macro

Say I want to use a macro that prepends \x to it's argument so that the replacement is a valid hex escape sequence, something like:

#define HEXIFY(s) "\x" s
...

std::cout << HEFIXY("48");

Or:

#define HEXIFY(s) "\x" #s
...

std::cout << HEXIFY(48);

Which would print the character H (hex 48).

Both of these snippets don't seem to work however. Is there a way I can accomplish this by only using macros?

Upvotes: 0

Views: 183

Answers (1)

monzie
monzie

Reputation: 565

#include <iostream>
using namespace std;
#define str(s) #s
#define XHEXIFY(x,y) (str(x##y))
#define HEXIFY(y) XHEXIFY(\x,y)

int main()
{
    cout<<HEXIFY(48)<<endl;
    return 0;
}

Upvotes: 2

Related Questions