Velocity Reviews > Using bitshift in assigning a number to a variable?

# Using bitshift in assigning a number to a variable?

pete
Guest
Posts: n/a

 12-27-2003
Robert Bachmann wrote:
>
> bollod wrote:
> > What would you do if you needed to create the mask '10101010' (besides
> > foo=170 or foo=0xA4)?

>
> I would write
> #define SOME_MASK (1<<7 | 1<<5 | 1<<3 | 1<<1)

Out of all of the various replies posted,
that form, shifts and bitwise ors,
is similar to macros that I've actually used.

--
pete

Sean Kenwrick
Guest
Posts: n/a

 12-27-2003
----- Original Message -----
From: "Richard Heathfield" <(E-Mail Removed)>
Newsgroups: comp.lang.c
Sent: 27 December 2003 11:12
Subject: Re: Using bitshift in assigning a number to a variable?

> bollod wrote:
>
> > On Fri, 26 Dec 2003 04:03:30 +0000, pete wrote:
> >
> >> It's easier to visualise the binary representation
> >> of the values that way,

> >
> > That makes sense.
> >
> > What would you do if you needed to create the mask '10101010' (besides
> > foo=170 or foo=0xA4)?

>
> #define l )*2+1
> #define O )*2
> #define b1 ((((((((0
>
> unsigned char foo = b1 l O l O l O l O ;
>

Hey this is pretty neat way of representing binary in your 'C' code. I
would generalise it a bit further by allowing 16 and 32 bit values as well,
something like:

#define bin32bit ((((((((((((((((((((((((((((((((0
#define bin16bit ((((((((((((((((0
#define bin8bit ((((((((0

#define O )<<1
#define I )<<1+1

Then

x=bin8bit I O I O I O I O

or

x = bin16bit I O I O I O I O I O I O I O I O

nice!

Sean

Richard Heathfield
Guest
Posts: n/a

 12-27-2003
Sean Kenwrick wrote:

> ----- Original Message -----
> From: "Richard Heathfield" <(E-Mail Removed)>
> Newsgroups: comp.lang.c
> Sent: 27 December 2003 11:12
> Subject: Re: Using bitshift in assigning a number to a variable?
>
>
>> bollod wrote:
>>
>> > On Fri, 26 Dec 2003 04:03:30 +0000, pete wrote:
>> >
>> >> It's easier to visualise the binary representation
>> >> of the values that way,
>> >
>> > That makes sense.
>> >
>> > What would you do if you needed to create the mask '10101010' (besides
>> > foo=170 or foo=0xA4)?

>>
>> #define l )*2+1
>> #define O )*2
>> #define b1 ((((((((0
>>
>> unsigned char foo = b1 l O l O l O l O ;
>>

>
> Hey this is pretty neat way of representing binary in your 'C' code. I
> would generalise it a bit further by allowing 16 and 32 bit values as
> well,

Yes, that's why I called it b1 rather than b - to allow for b2 and b4 (and,
if you have bigger integral types, b8 and so on as well).

See "Expert C Programming (Deep C Secrets)" by Peter van der Linden, p203,
for the original idea. All I did was hack the names.

--
Richard Heathfield : http://www.velocityreviews.com/forums/(E-Mail Removed)
"Usenet is a strange place." - Dennis M Ritchie, 29 July 1999.
C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
K&R answers, C books, etc: http://users.powernet.co.uk/eton