Subject:
|
Re: converting binary to integer
|
Newsgroups:
|
lugnet.robotics.handyboard
|
Date:
|
Wed, 4 Jun 1997 07:51:13 GMT
|
Original-From:
|
root <root@snotnose./StopSpam/wizard.org>
|
Viewed:
|
1303 times
|
| |
| |
> At 12:40 AM 6/4/97 -0400, you wrote:
> > I am reading four digital inputs and I need a way to convert those four
> > bits into a decimal number. Is there an easy way to do it. Thanks.
> >
> > Keith
> >
> > Keith Soldavin
> >
> >
> Multiply each bit by 2^n, where n is the "place" of the number. Then add
> the products together. For example...
>
> 1011 = 1*2^0 + 1*2^1 + 0*2^2 + 1*2^3 = 11
>
> The "zero" place is the one furthest to the right, and you work left from
> there.
> --------------------------------
> Jeff Keyzer
You can always read the port directly like so:
(int) data = peek(0x7000);
If the bits you're interested in happen to start with the 'least-significant-
bit' (LSB) and continue consecutively (eg 0b00000111) where the 1's are the
bits you're interested in- then the "result" of the peek() will be a decimal
number from 0 to (2^(MSB+1)-1) or in this case from 0 to 7. MSB means 'most-
significant-bit' or the highest numbered bit (counting from zero) that you're
using. If you need non-consecutive bits you could do something like:
(int) data = peek(0x7000) & bits;
where 'bits' is a predefined set of bits you are interested in- ie. something
like '0b11110000' where the 1 bits are the ones you're interested in. The
decimal number you'll get as the "result" will not be consecutive though. If
you wanted the upper four (or some consecutive set not starting at the zero
bit) you could simply shift them right an appropriate number of bit positions
to get a consecutive decimal number conforming to the little formula above:
(int) data = (peek(0x7000) & bits) >> places;
where places is the proper number of positions to shift. If you want to check
to see if a particular bit is set in a value you can do something like:
(int) result = data & bit;
where bit is the one you're interested in (eg. 0b00100000). If result is NOT
zero (in fact, the value of the bit you're interested in by coincidence!) the
bit is set. If the result IS zero the bit is not set.
Hope this helps.
John Whitten
brat@naxs.com
|
|
1 Message in This Thread:
- Entire Thread on One Page:
- Nested:
All | Brief | Compact | Dots
Linear:
All | Brief | Compact
|
|
|
|