Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.c > #16317 > unrolled thread

bitwise operators(info)

Started byCeriousmall <divadsmall@gmail.com>
First post2012-01-27 13:56 -0800
Last post2012-01-27 21:44 -0700
Articles 20 on this page of 25 — 14 participants

Back to article view | Back to comp.lang.c


Contents

  bitwise operators(info) Ceriousmall <divadsmall@gmail.com> - 2012-01-27 13:56 -0800
    Re: bitwise operators(info) John Gordon <gordon@panix.com> - 2012-01-27 22:03 +0000
    Re: bitwise operators(info) "Morris Keesan" <mkeesan@post.harvard.edu> - 2012-01-27 17:35 -0500
      Re: bitwise operators(info) Ceriousmall <divadsmall@gmail.com> - 2012-01-27 16:22 -0800
    Re: bitwise operators(info) Devil with the China Blue Dress <chine.bleu@yahoo.com> - 2012-01-27 16:52 -0800
      Re: bitwise operators(info) Keith Thompson <kst-u@mib.org> - 2012-01-27 17:06 -0800
        Re: bitwise operators(info) Harald van Dijk <truedfx@gmail.com> - 2012-01-27 19:06 -0800
          Re: bitwise operators(info) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2012-01-28 11:33 +0000
            Re: bitwise operators(info) James Kuyper <jameskuyper@verizon.net> - 2012-01-28 13:46 -0500
              Re: bitwise operators(info) Kaz Kylheku <kaz@kylheku.com> - 2012-01-28 19:01 +0000
              Re: bitwise operators(info) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2012-01-28 22:41 +0000
                Re: bitwise operators(info) Ceriousmall <divadsmall@gmail.com> - 2012-01-28 21:19 -0800
                  Re: bitwise operators(info) Keith Thompson <kst-u@mib.org> - 2012-01-29 02:13 -0800
                  Re: bitwise operators(info) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2012-01-29 14:59 +0000
                    Re: bitwise operators(info) pete <pfiland@mindspring.com> - 2012-01-29 10:51 -0500
                  Re: bitwise operators(info) ImpalerCore <jadill33@gmail.com> - 2012-01-30 10:25 -0800
                    Re: bitwise operators(info) Ceriousmall <divadsmall@gmail.com> - 2012-01-31 06:00 -0800
                      Re: bitwise operators(info) Ben Bacarisse <ben.usenet@bsb.me.uk> - 2012-01-31 14:30 +0000
                        Re: bitwise operators(info) pete <pfiland@mindspring.com> - 2012-01-31 10:06 -0500
            Re: bitwise operators(info) Harald van Dijk <truedfx@gmail.com> - 2012-01-28 12:34 -0800
        Re: bitwise operators(info) Eric Sosman <esosman@ieee-dot-org.invalid> - 2012-01-27 22:56 -0500
          Re: bitwise operators(info) Keith Thompson <kst-u@mib.org> - 2012-01-27 20:30 -0800
            Re: bitwise operators(info) Shao Miller <sha0.miller@gmail.com> - 2012-01-29 09:27 -0500
          Re: bitwise operators(info) Kaz Kylheku <kaz@kylheku.com> - 2012-01-28 05:16 +0000
    Re: bitwise operators(info) Joe Pfeiffer <pfeiffer@cs.nmsu.edu> - 2012-01-27 21:44 -0700

Page 1 of 2  [1] 2  Next page →


#16317 — bitwise operators(info)

FromCeriousmall <divadsmall@gmail.com>
Date2012-01-27 13:56 -0800
Subjectbitwise operators(info)
Message-ID<96da10c2-5084-44fe-a0b1-dfd3d145e36f@eb6g2000vbb.googlegroups.com>
Can anyone here point me towards any documentation that explains
bitwise operations in C in a simple manner. After K&R Chap 2.9
introduction to the bitwise operator I'm still in the dark. Basically
I take out my paper take two integers convert them into their binary
form and  compare them using the rules of the bitwise operartors to
yield a result then convert that value back to decimal.......

[toc] | [next] | [standalone]


#16318

FromJohn Gordon <gordon@panix.com>
Date2012-01-27 22:03 +0000
Message-ID<jfv705$bq7$1@reader1.panix.com>
In reply to#16317
In <96da10c2-5084-44fe-a0b1-dfd3d145e36f@eb6g2000vbb.googlegroups.com> Ceriousmall <divadsmall@gmail.com> writes:

> Can anyone here point me towards any documentation that explains
> bitwise operations in C in a simple manner. After K&R Chap 2.9

http://www.cprogramming.com/tutorial/bitwise_operators.html

-- 
John Gordon                   A is for Amy, who fell down the stairs
gordon@panix.com              B is for Basil, assaulted by bears
                                -- Edward Gorey, "The Gashlycrumb Tinies"

[toc] | [prev] | [next] | [standalone]


#16320

From"Morris Keesan" <mkeesan@post.harvard.edu>
Date2012-01-27 17:35 -0500
Message-ID<op.v8rk1hbo5qv6o3@toshiba-laptop>
In reply to#16317
On Fri, 27 Jan 2012 16:56:36 -0500, Ceriousmall <divadsmall@gmail.com>  
wrote:

> Can anyone here point me towards any documentation that explains
> bitwise operations in C in a simple manner. After K&R Chap 2.9
> introduction to the bitwise operator I'm still in the dark. Basically
> I take out my paper take two integers convert them into their binary
> form and  compare them using the rules of the bitwise operartors to
> yield a result then convert that value back to decimal.......

The main place where you're going wrong here is in converting the value
back to decimal.  I've found that in general, if I'm using bitwise
operations, I'm probably just interested in the individual bits of a
value, not in the numerical value of the entire number.  E.g. various
Unix system calls deal with int values which are collections of flag
bits, so if you wanted to query the value of a flag you would use the
'&' operator, e.g.
     if (my_flags & SOME_FLAG_BIT) { /* do something */ }
If you wanted to turn on that flag, it would be
     my_flags |= SOME_FLAG_BIT
and to turn it off would be
     my_flags &= ~SOME_FLAG_BIT

where SOME_FLAG_BIT is probably #defined as a power of two, typically
using an octal or hexadecimal constant, e.g.

#define FLAG_A 001
#define FLAG_B 002
#define FLAG_C 004
#define FLAG_D 010
etc.



-- 
Morris Keesan -- mkeesan@post.harvard.edu

[toc] | [prev] | [next] | [standalone]


#16325

FromCeriousmall <divadsmall@gmail.com>
Date2012-01-27 16:22 -0800
Message-ID<719b1436-ae01-4cb1-b29a-b66531d446f4@e27g2000vbu.googlegroups.com>
In reply to#16320
Thanks for all the feed-back and the tutorial has been very
enlightening. Ive been at this all day from binary to hex to octal but
I'm beginning to get a grasp  of it now.

[toc] | [prev] | [next] | [standalone]


#16328

FromDevil with the China Blue Dress <chine.bleu@yahoo.com>
Date2012-01-27 16:52 -0800
Message-ID<chine.bleu-83BB34.16524127012012@news.eternal-september.org>
In reply to#16317
In article <96da10c2-5084-44fe-a0b1-dfd3d145e36f@eb6g2000vbb.googlegroups.com>,
 Ceriousmall <divadsmall@gmail.com> wrote:

> Can anyone here point me towards any documentation that explains
> bitwise operations in C in a simple manner. After K&R Chap 2.9
> introduction to the bitwise operator I'm still in the dark. Basically
> I take out my paper take two integers convert them into their binary
> form and  compare them using the rules of the bitwise operartors to
> yield a result then convert that value back to decimal.......

If your number is an int, it is already in binary on any machine you're likely 
to be using. You can use sscanf and sprintf to convert a decimal integer string 
to/from a binary int.

-- 
My name Indigo Montoya.      |         It's Coraline, not Caroline.
You flamed my father.        |       I'm whoever you want me to be.
Prepare to be spanked.       |  Annoying Usenet one post at a time.
Stop posting that!           |    At least I can stay in character.

[toc] | [prev] | [next] | [standalone]


#16331

FromKeith Thompson <kst-u@mib.org>
Date2012-01-27 17:06 -0800
Message-ID<lnzkd81vqy.fsf@nuthaus.mib.org>
In reply to#16328
Devil with the China Blue Dress <chine.bleu@yahoo.com> writes:
> In article <96da10c2-5084-44fe-a0b1-dfd3d145e36f@eb6g2000vbb.googlegroups.com>,
>  Ceriousmall <divadsmall@gmail.com> wrote:
>> Can anyone here point me towards any documentation that explains
>> bitwise operations in C in a simple manner. After K&R Chap 2.9
>> introduction to the bitwise operator I'm still in the dark. Basically
>> I take out my paper take two integers convert them into their binary
>> form and  compare them using the rules of the bitwise operartors to
>> yield a result then convert that value back to decimal.......
>
> If your number is an int, it is already in binary on any machine you're likely 
> to be using. You can use sscanf and sprintf to convert a decimal integer string 
> to/from a binary int.

In fact an int is represented in binary on any conforming
implementation; see C99 6.2.6.2.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
    Will write code for food.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

[toc] | [prev] | [next] | [standalone]


#16336

FromHarald van Dijk <truedfx@gmail.com>
Date2012-01-27 19:06 -0800
Message-ID<42dacbf3-7657-44e2-b9b8-1be8e49651f8@t8g2000yqg.googlegroups.com>
In reply to#16331
On Jan 28, 2:06 am, Keith Thompson <ks...@mib.org> wrote:
> Devil with the China Blue Dress <chine.b...@yahoo.com> writes:
> > If your number is an int, it is already in binary on any machine you're likely
> > to be using. You can use sscanf and sprintf to convert a decimal integer string
> > to/from a binary int.
>
> In fact an int is represented in binary on any conforming
> implementation; see C99 6.2.6.2.

Only in the abstract machine. An integer may for example, in a
concrete translation of a program, very well be represented as a
string/float if the implementation determines that the value will not
be used for anything else than a conversion to a string/float. Or a
compiler may load an integer in a floating point register, because a
floating point register happens to be available and all integer
registers are already in use. Or, although I doubt it would be a good
idea, a conforming implementation of C could be created for a ternary
machine, converting behind the scenes between binary and ternary as
required.

[toc] | [prev] | [next] | [standalone]


#16350

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2012-01-28 11:33 +0000
Message-ID<0.e41cbc1eedd06ab4387e.20120128113315GMT.874nvg3vus.fsf@bsb.me.uk>
In reply to#16336
Harald van Dijk <truedfx@gmail.com> writes:

> On Jan 28, 2:06 am, Keith Thompson <ks...@mib.org> wrote:
>> Devil with the China Blue Dress <chine.b...@yahoo.com> writes:
>> > If your number is an int, it is already in binary on any machine you're likely
>> > to be using. You can use sscanf and sprintf to convert a decimal integer string
>> > to/from a binary int.
>>
>> In fact an int is represented in binary on any conforming
>> implementation; see C99 6.2.6.2.
>
> Only in the abstract machine.

Surely that's a misuse of "only"?  Something that is "only" true in C's
abstract machine, it true as far as any conforming C program in
concerned.

> An integer may for example, in a
> concrete translation of a program, very well be represented as a
> string/float if the implementation determines that the value will not
> be used for anything else than a conversion to a string/float. Or a
> compiler may load an integer in a floating point register, because a
> floating point register happens to be available and all integer
> registers are already in use. Or, although I doubt it would be a good
> idea, a conforming implementation of C could be created for a ternary
> machine, converting behind the scenes between binary and ternary as
> required.

That's all true, but I'd still say that the numbers are represented in
binary because that whole idea is an abstract one.  Look deep enough
into any implementation and the binary data vanishes eventually.  It's
the abstractions that matter to programmers.

-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#16359

FromJames Kuyper <jameskuyper@verizon.net>
Date2012-01-28 13:46 -0500
Message-ID<jg1fpk$s1q$1@dont-email.me>
In reply to#16350
On 01/28/2012 06:33 AM, Ben Bacarisse wrote:
> Harald van Dijk <truedfx@gmail.com> writes:
> 
>> On Jan 28, 2:06 am, Keith Thompson <ks...@mib.org> wrote:
...
>>> In fact an int is represented in binary on any conforming
>>> implementation; see C99 6.2.6.2.
>>
>> Only in the abstract machine.
> 
> Surely that's a misuse of "only"?  Something that is "only" true in C's
> abstract machine, it true as far as any conforming C program in
> concerned.

No, things that are true in the abstract machine may be false in the
real machine. All that's actually required is that the C implementation
produce the same results as it would if they were true. That's the whole
point of the concept of the abstract machine.
-- 
James Kuyper

[toc] | [prev] | [next] | [standalone]


#16361

FromKaz Kylheku <kaz@kylheku.com>
Date2012-01-28 19:01 +0000
Message-ID<20120128105837.64@kylheku.com>
In reply to#16359
On 2012-01-28, James Kuyper <jameskuyper@verizon.net> wrote:
> On 01/28/2012 06:33 AM, Ben Bacarisse wrote:
>> Harald van Dijk <truedfx@gmail.com> writes:
>> 
>>> On Jan 28, 2:06 am, Keith Thompson <ks...@mib.org> wrote:
> ...
>>>> In fact an int is represented in binary on any conforming
>>>> implementation; see C99 6.2.6.2.
>>>
>>> Only in the abstract machine.
>> 
>> Surely that's a misuse of "only"?  Something that is "only" true in C's
>> abstract machine, it true as far as any conforming C program in
>> concerned.
>
> No, things that are true in the abstract machine may be false in the
> real machine.

Perhaps:

Things that are true OF the abstract machine may be false OF the real
machine.

Things that are true IN the abstract machine are true IN the real one.

> All that's actually required is that the C implementation
> produce the same results as it would if they were true. That's the whole
> point of the concept of the abstract machine.

Determining what the output should be is an overwhelmingly large
and broadly encompassing point. :)

[toc] | [prev] | [next] | [standalone]


#16372

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2012-01-28 22:41 +0000
Message-ID<0.2835a3ac4e2fe672524d.20120128224118GMT.87r4yj30xd.fsf@bsb.me.uk>
In reply to#16359
James Kuyper <jameskuyper@verizon.net> writes:

> On 01/28/2012 06:33 AM, Ben Bacarisse wrote:
>> Harald van Dijk <truedfx@gmail.com> writes:
>> 
>>> On Jan 28, 2:06 am, Keith Thompson <ks...@mib.org> wrote:
> ...
>>>> In fact an int is represented in binary on any conforming
>>>> implementation; see C99 6.2.6.2.
>>>
>>> Only in the abstract machine.
>> 
>> Surely that's a misuse of "only"?  Something that is "only" true in C's
>> abstract machine, it true as far as any conforming C program in
>> concerned.
>
> No, things that are true in the abstract machine may be false in the
> real machine.

True (except for the peculiar choice of the first word).

> All that's actually required is that the C implementation
> produce the same results as it would if they were true.

Yup.

> That's the whole
> point of the concept of the abstract machine.

Indeed.  Where is it that you are disagreeing with me, or did you mean
to start "Yes, things that are true..."?

-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#16382

FromCeriousmall <divadsmall@gmail.com>
Date2012-01-28 21:19 -0800
Message-ID<5275606b-2eef-4e1d-9bd5-7ad2b454778e@x6g2000pbk.googlegroups.com>
In reply to#16372
(K&R Exercise 2-6)
Write a function setbits(x,p,n,y) that returns x with the n bits that
begin
at position p set to the rightmost n bits of y, leaving the other bits
unchanged.

** p set to the rightmost n bits of y ** This has me at a loss as to
he role
of P. P is passed to the function as one value then reset to the n
most of y

my code thus far......
unsigned setbits(unsigned x, int p, int n, unsigned y)
{
	unsigned mask = ~(~0 << n);

        ***************************************
	*  /* p = y & mask; */                *
        *  /* return x & (mask << (p+1-n)) */ *
        *       first attempt                 *
        ***************************************
return x & (mask << ((((p & 0) | mask) & y)+1-n));
}  second attempt and still trying

Im not looking for the answer as I'd really like to work this out for
myself but rather some pointers on where I'm going wrong here or where
my interpretation has gone wrong.

[toc] | [prev] | [next] | [standalone]


#16383

FromKeith Thompson <kst-u@mib.org>
Date2012-01-29 02:13 -0800
Message-ID<lnwr8azuiv.fsf@nuthaus.mib.org>
In reply to#16382
Ceriousmall <divadsmall@gmail.com> writes:
> return x & (mask << ((((p & 0) | mask) & y)+1-n));
[...]

p & 0 is always 0.

-- 
Keith Thompson (The_Other_Keith) kst-u@mib.org  <http://www.ghoti.net/~kst>
    Will write code for food.
"We must do something.  This is something.  Therefore, we must do this."
    -- Antony Jay and Jonathan Lynn, "Yes Minister"

[toc] | [prev] | [next] | [standalone]


#16390

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2012-01-29 14:59 +0000
Message-ID<0.39c22a4cda991bf5217b.20120129145931GMT.874nve367g.fsf@bsb.me.uk>
In reply to#16382
Ceriousmall <divadsmall@gmail.com> writes:

I've fixed up line breaks.  There's something odd about the look of your
posts.

> (K&R Exercise 2-6)
> Write a function setbits(x,p,n,y) that returns x with the n bits that
> begin at position p set to the rightmost n bits of y, leaving the
> other bits unchanged.
>
> ** p set to the rightmost n bits of y ** This has me at a loss as to
> [t]he role of P. P is passed to the function as one value then reset
> to the n most of y

No, p is not set at all.  Your quote "p set to the rightmost bits..." is
out of context.  Its is "the n bits that begin at position p" that get
set.

> my code thus far......
> unsigned setbits(unsigned x, int p, int n, unsigned y)

Good.  Always do bit operations on unsigned quantities if you can.
Personally, I'd also make n and p unsigned since it makes no sense to
call setbits with either n or p < 0.

> {
> 	unsigned mask = ~(~0 << n);
>
>         ***************************************
> 	*  /* p = y & mask; */                *
>         *  /* return x & (mask << (p+1-n)) */ *
>         *       first attempt                 *
>         ***************************************
> return x & (mask << ((((p & 0) | mask) & y)+1-n));
> }  second attempt and still trying
>
> Im not looking for the answer as I'd really like to work this out for
> myself but rather some pointers on where I'm going wrong here or where
> my interpretation has gone wrong.

Try something simpler.  Soon the exercise will itself look simple.
First, write a function clearbits(x, p, n) that returns x with the n
bits starting at position n cleared (zeroed).  If that's too tricky,
image what you'd write if p was always zero.  How would that code have
to change when p > 0?

Next write rightmost(y, n) that returns the right-most n bits of y.  How
can you use rightmost and clearbits to write setbits?

-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#16393

Frompete <pfiland@mindspring.com>
Date2012-01-29 10:51 -0500
Message-ID<4F256AF6.2BCB@mindspring.com>
In reply to#16390
Ben Bacarisse wrote:
> 
> Ceriousmall <divadsmall@gmail.com> writes:
> 
> I've fixed up line breaks.
> There's something odd about the look of your posts.
> 
> > (K&R Exercise 2-6)
> > Write a function setbits(x,p,n,y)
> > that returns x with the n bits that
> > begin at position p set to the rightmost n bits of y, leaving the
> > other bits unchanged.
> >
> > ** p set to the rightmost n bits of y ** This has me at a loss as to
> > [t]he role of P. P is passed to the function as one value then reset
> > to the n most of y
> 
> No, p is not set at all.
> Your quote "p set to the rightmost bits..." is
> out of context.  Its is "the n bits that begin at position p" that get
> set.
> 
> > my code thus far......
> > unsigned setbits(unsigned x, int p, int n, unsigned y)
> 
> Good.  Always do bit operations on unsigned quantities if you can.
> Personally, I'd also make n and p unsigned since it makes no sense to
> call setbits with either n or p < 0.

I agree.

> 
> > {
> >       unsigned mask = ~(~0 << n);

The above line likely contains indefined behavior.

(~0) is a negative value of type (int),
except in a ones complement system which supports negative zeros.
The left shift of a negative value of type (int) is undefined.

However, (~0u) is equal to (UINT_MAX).


> >
> >         ***************************************
> >       *  /* p = y & mask; */                *
> >         *  /* return x & (mask << (p+1-n)) */ *
> >         *       first attempt                 *
> >         ***************************************
> > return x & (mask << ((((p & 0) | mask) & y)+1-n));
> > }  second attempt and still trying
> >
> > Im not looking for the answer
> > as I'd really like to work this out for
> > myself but rather some pointers
> > on where I'm going wrong here or where
> > my interpretation has gone wrong.
> 
> Try something simpler.  Soon the exercise will itself look simple.
> First, write a function clearbits(x, p, n) that returns x with the n
> bits starting at position n cleared (zeroed).  If that's too tricky,
> image what you'd write if p was always zero.  How would that code have
> to change when p > 0?
> 
> Next write rightmost(y, n) 
> that returns the right-most n bits of y.  How
> can you use rightmost and clearbits to write setbits?



-- 
pete

[toc] | [prev] | [next] | [standalone]


#16448

FromImpalerCore <jadill33@gmail.com>
Date2012-01-30 10:25 -0800
Message-ID<1dc09d6b-8ea7-4122-905d-c57baf27e673@w4g2000vbc.googlegroups.com>
In reply to#16382
On Jan 29, 12:19 am, Ceriousmall <divadsm...@gmail.com> wrote:
> (K&R Exercise 2-6)
> Write a function setbits(x,p,n,y) that returns x with the n bits that
> begin
> at position p set to the rightmost n bits of y, leaving the other bits
> unchanged.
>
> ** p set to the rightmost n bits of y ** This has me at a loss as to
> he role
> of P. P is passed to the function as one value then reset to the n
> most of y

When faced with difficulty, it often helps to start with a concrete
example.

Let me rename the variables a little bit.  Having this many single
letter variables is awful for the next person who needs to read it.

setbits( word, index, width, field )

Consider an unsigned 32-bit integer 'word' with the value 0x76543210.
It's binary representation is

0111 0110 0101 0100 0011 0010 0001 0000

Within the 'word', there is a 'field' of 'width' 8 that you want to
set, let's say 0xA1.  It's binary representation is

0000 0000 0000 0000 0000 0000 1010 0001
                              \       /
                               width=8

For a given 'index' (12) in 'word', set the corresponding bits in
'word' so that the final result is '0x765 A1 210' or

msb                                 lsb
0111 0110 0101 1010 0001 0010 0001 0000
                        \
                       index

Think of this as a two part problem.  The first problem is to clear
out the bits in 'word' where the 'field' will be inserted.  The second
problem is to insert the 'field' into 'word' at the right index.

Hint: For the problem above, try to setup the following.

0111 0110 0101 0000 0000 0010 0001 0000

and

0000 0000 0000 1010 0001 0000 0000 0000

Once you get one concrete example working, test it on other examples
to see if you need to make adjustments to your algorithm.

> my code thus far......
> unsigned setbits(unsigned x, int p, int n, unsigned y)
> {
>         unsigned mask = ~(~0 << n);
>
>         ***************************************
>         *  /* p = y & mask; */                *
>         *  /* return x & (mask << (p+1-n)) */ *
>         *       first attempt                 *
>         ***************************************
> return x & (mask << ((((p & 0) | mask) & y)+1-n));
>
> }  second attempt and still trying
>
> Im not looking for the answer as I'd really like to work this out for
> myself but rather some pointers on where I'm going wrong here or where
> my interpretation has gone wrong.

One issue with using '~0' is that the type is restricted to 'int'.  If
'int' is 16 bits, and you want to set a field in a 32-bit long, it's
not going to come out right.  What I do is define a constant that
defines the mask so that it's easy to change if I need to support bit
operations on larger integer types.

\code snippet
/*!
 * \brief Define the integer type used to create a bitmask of all
 *        ones.
 *
 * One of the basic constructs used in the \c bits macro library is
 * to create a mask that is all ones of a given width starting from
 * the least significant bit.  This is implemented using the
 * expression <tt>~((~0) << width)</tt>.  This is used to isolate a
 * region of bits to be set or cleared within an integer.  This
 * concept is needed to implement the set of \c BIT_FIELD macros.
 *
 * The \c C_BITS_ALL_ONES define can be \c ~0U for \c int sized
 * masks, <tt>~UINT32_C(0)</tt> to enable 32-bit support on 16-bit
 * integer platforms, or <tt>~UINT64_C(0)</tt> to enable 64-bit
 * support.  This could be configured using a Makefile or config.h,
 * but for now its definition is here.
 *
 * See \ref C_BITS_ONE for more information.
 */
#define C_BITS_ALL_ONES ( ~UINT32_C(0) )
\endcode

The motivation for 'setbits' is to be able to pack information at the
bit level from several different pieces of data.  For example, in
avionics data, the ARINC 429 data standard packs 5 bits of information
into a single 32-bit word.

\comment snippet
/*
 * The ARINC 429 standard is a point to point protocol consisting
 * of a twisted pair that transmits 32-bit messages from avionics
 * devices on an aircraft.  The data bus consists of one source with
 * many potential receivers.  The following is a description of the
 * meaning of the message fields.
 *
 * <ul>
 *   <li> \c label  - This identifies the data type and the
 *                    parameters associated with it for representing
 *                    avionics data.  A single avionics device may
 *                    have up to 256 different messages.
 *   <li> \c sdi    - This field is used for multiple receivers to
 *                    identify which receiver is the recipient of
 *                    the avionics data.
 *   <li> \c data   - The avionics data, represented in a number of
 *                    different formats.  The common ones are binary
 *                    coded decimal, 2's complement binary, and bit
 *                    fields.
 *   <li> \c ssm    - This field contains hardware equipment
 *                    conditions, operational mode, or validity of
 *                    data content.
 *   <li> \c parity - The most significant bit is the parity bit,
 *                    typically used to ensure the ARINC 429 message
 *                    has odd parity.  Whether this bit is used
 *                    depends on the avionic system design.
 * </ul>
 *
 * Let's look at a real ARINC 429 standard message from an Air Data
 * Computer (ADC).  The labels are represented in octal form.
 *
 * Total Air Temperature
 * <ul>
 *   <li> Bit:  1 -  8  Name: Label (211)
 *   <li> Bit:  9 - 10  Name: SDI
 *   <li> Bit: 11 - 17  Name: Spare
 *   <li> Bit: 18 - 29  Name: Total Air Temperature Value \n
 *     <ul>
 *       <li> Element Size: 12
 *       <li> Type: 2's Complement
 *       <li> Units: Degrees C
 *       <li> Scale: .25
 *       <li> State: [-60, 100]
 *     </ul>
 *   <li> Bit: 30 - 31  Name: SSM
 *   <li> Bit: 32       Name: Parity
 * </ul>
 */
\endcomment

So, if you wanted to simulate an ARINC 429 data stream, you could take
an array of floating point temperatures in celsius, factor out the
scale factor to convert it to a 2's complement integer representation,
and use 'setbits' to place the 'Total Air Temperature' value's bits at
the right location in the ARINC 429 data word.  You can use 'setbits'
to fill in the rest of the fields (Label, SSM, SDI) as needed.

Best regards,
John D.

[toc] | [prev] | [next] | [standalone]


#16487

FromCeriousmall <divadsmall@gmail.com>
Date2012-01-31 06:00 -0800
Message-ID<f8df09c6-2f38-4688-a106-9820eaab9e5d@3g2000pbd.googlegroups.com>
In reply to#16448
Guys I wanna say thanks for all the help and pointers with this
bitwise exercise.
This is the code I've come up with.......

unsigned setbits(unsigned x, int p, int n, unsigned y)
{
     unsigned mask = ~(~0 << n);

     return x & ~(mask << (p+1-n)) | ((y & mask) << (p+1-n));
}

[toc] | [prev] | [next] | [standalone]


#16491

FromBen Bacarisse <ben.usenet@bsb.me.uk>
Date2012-01-31 14:30 +0000
Message-ID<0.607f527ed9c598351925.20120131143011GMT.878vkoq70s.fsf@bsb.me.uk>
In reply to#16487
Ceriousmall <divadsmall@gmail.com> writes:

> Guys I wanna say thanks for all the help and pointers with this
> bitwise exercise.

You missed a bit of advice...

> This is the code I've come up with.......
>
> unsigned setbits(unsigned x, int p, int n, unsigned y)
> {
>      unsigned mask = ~(~0 << n);

~0 has (on all the machines you are likely to come across[1]) a value
less than zero.  Shifting a negative value left is undefined even though
it may work.  It's better, therefore, to write:

  unsigned mask = ~(~0u << n);

and there are other ways too: ~(-1u << n) and ~(UINT_MAX << n) for
example.

>      return x & ~(mask << (p+1-n)) | ((y & mask) << (p+1-n));
> }

Since the exercise did not specify how the bits are numbered, you don't
have to use such a complex shift expression.  I'd argue that

  return x & ~(mask << p) | ((y & mask) << p);

meets the spec. perfectly well but there's nothing wrong with your
way.  Well done!

[1] I don't want to get into an argument as to whether -0 is a
"nonnegative value" for the purposes of 6.5.7p4.
-- 
Ben.

[toc] | [prev] | [next] | [standalone]


#16495

Frompete <pfiland@mindspring.com>
Date2012-01-31 10:06 -0500
Message-ID<4F280377.2EDA@mindspring.com>
In reply to#16491
Ben Bacarisse wrote:
 
> [1] I don't want to get into an argument as to whether -0 is a
> "nonnegative value" for the purposes of 6.5.7p4.

I was wondering about that.

I think that negative zero is not a negative value.

But I think that for the purposes of bitwise operators,
it might make more sense to consider negative zero
as a negative value.

-- 
pete

[toc] | [prev] | [next] | [standalone]


#16364

FromHarald van Dijk <truedfx@gmail.com>
Date2012-01-28 12:34 -0800
Message-ID<86f0911a-65a2-4541-a55d-2fc6853bb145@o13g2000vbf.googlegroups.com>
In reply to#16350
On Jan 28, 12:33 pm, Ben Bacarisse <ben.use...@bsb.me.uk> wrote:
> Harald van Dijk <true...@gmail.com> writes:
> > On Jan 28, 2:06 am, Keith Thompson <ks...@mib.org> wrote:
> >> Devil with the China Blue Dress <chine.b...@yahoo.com> writes:
> >> > If your number is an int, it is already in binary on any machine you're likely
> >> > to be using. You can use sscanf and sprintf to convert a decimal integer string
> >> > to/from a binary int.
>
> >> In fact an int is represented in binary on any conforming
> >> implementation; see C99 6.2.6.2.
>
> > Only in the abstract machine.
>
> Surely that's a misuse of "only"?  Something that is "only" true in C's
> abstract machine, it true as far as any conforming C program in
> concerned.

Pretty much, yes. I didn't read Devil with the China Blue Dress's
message as applying to the abstract machine, so I objected to a
correction that did. I fully agree with you that an otherwise strictly
conforming program must not be able to tell the difference, so from
the point of view of anyone writing C code, it doesn't matter.

[toc] | [prev] | [next] | [standalone]


Page 1 of 2  [1] 2  Next page →

Back to top | Article view | comp.lang.c


csiph-web