Re: How to convert binary to hex using a macro?
- From: Micah Cowan <micah@xxxxxxxxxx>
- Date: Fri, 24 Feb 2006 22:19:22 GMT
Jordan Abel <random832@xxxxxxxxx> writes:
On 2006-02-24, Jordan Abel <random832@xxxxxxxxx> wrote:
On 2006-02-24, Micah Cowan <micah@xxxxxxxxxx> wrote:
Jordan Abel <random832@xxxxxxxxx> writes:
#define PASTE(a,b)a##b
#define PASTE2(a,b)PASTE(a,b)
#define x(y)y
#define HEX_(x)PASTE(HEX_,x)
#define Ox(x)PASTE(0x,x)
#define HEX_0100 4
#define HEX_0010 2
#define HEX(x)
#define BINARY4(x)Ox(HEX_(x))
#define BINARY8(x,y)PASTE2(BINARY4(x),HEX_(y))
BINARY4(0100)
BINARY8(0100,0010)
Playing around until it works is not usually a good way to generate
portable code. In your case, it has. But note that the x() macro above
isn't actually used anywhere, so it could be eliminated. Also, you
could eliminate HEX_() and 0x() by simply using PASTE2() directly:
it's the indirection that forces the arguments to be recursively
expanded. When a parameter is encountered after a # or next to a ##,
it will /not/ be macro-replaced, which is why the original
COMBINE(HEX_(a)) /must/ produce 0xHEX_(a) (which, since it isn't
defined as a macro, won't be further replaced).
I tried to use HEX_ and Ox to provide the extra level of indirection -
any idea why it didn't work?
I thought you said it /did/ work. It does for me, and looks fine, if
verbose. I just meant you don't need the HEX_() and 0x() macros
weren't necessary: PASTE2() provides adequate indirection.
Also, why doesn't
#define PASTE(a,b) a/**/b
make it provide correct results in K&R mode? It's not particularly
important, but I was curious.
As to that... the Standard requires that comments be treated as a
single space. AFAIK, in K&R days it probably was up to the
implementation to decide whether this would result in "token pasting"
or a single space. Someone with a good deal more experience in K&R C
should probably speak up now.
.
- Follow-Ups:
- Re: How to convert binary to hex using a macro?
- From: Jordan Abel
- Re: How to convert binary to hex using a macro?
- From: Jordan Abel
- Re: How to convert binary to hex using a macro?
- References:
- How to convert binary to hex using a macro?
- From: Chen Shu
- Re: How to convert binary to hex using a macro?
- From: Jordan Abel
- Re: How to convert binary to hex using a macro?
- From: Micah Cowan
- Re: How to convert binary to hex using a macro?
- From: Jordan Abel
- Re: How to convert binary to hex using a macro?
- From: Jordan Abel
- How to convert binary to hex using a macro?
- Prev by Date: Re: I'm not understanding something
- Next by Date: Re: I'm not understanding something
- Previous by thread: Re: How to convert binary to hex using a macro?
- Next by thread: Re: How to convert binary to hex using a macro?
- Index(es):
Relevant Pages
|