Re: bits from bytes [message #10666 is a reply to message #10660] |
Fri, 19 December 1997 00:00  |
davidf
Messages: 2866 Registered: September 1996
|
Senior Member |
|
|
Kelly Dean (krdean@lamar.colostate.edu) writes:
> I need to extract the first 3 bits from a byte.
> Any suggestions?
If I am sure of anything, I am sure this is NOT the way
to do this. :-)
But you reminded me I had this program lying around here
waiting for a reason to use it. One night not too long ago
I couldn't sleep and for some reason (this is really *weird*)
I began to wonder what the binary representation of a certain
number was. Don't ask me why, I couldn't tell you. It seemed
important in that strange twilight time between when you begin
to lose consciousness and really fall asleep. Do you know what
I mean?
Anyway, I wanted to know. So I wrote this IDL program the
next morning. I guess you could figure out how to use
it to extract the first three bits from a byte, if you
wanted to. Or, you could wait for Kevin Ivory to send you
the *real* answer. :-)
If I have the byte value 5, I would use it like this:
Print, Binary(5B)
It prints out: 0 0 0 0 0 1 0 1.
Happy Holidays!
David
***********************************************************
FUNCTION BINARY, number
; This function returns the binary representation
; of a number. Numbers are converted to LONG integers
; if necessary.
On_Error, 1
s = SIZE(number)
type = s[s[0] + 1]
IF type EQ 0 THEN Message, 'Number parameter must be defined.'
IF type EQ 1 OR type EQ 2 THEN BEGIN
bin = STRARR(8*type)
FOR j=0,(type*8)-1 DO BEGIN
powerOfTwo = 2L^j
IF (LONG(number) AND powerOfTwo) EQ powerOfTwo THEN $
bin(j) = '1' ELSE bin(j) = '0'
ENDFOR
ENDIF ELSE BEGIN
Print, 'Converting "number" to LONG...'
number = LONG(number)
bin = STRARR(32)
FOR j=0,31 DO BEGIN
powerOfTwo = 2L^j
IF (LONG(number) AND powerOfTwo) EQ powerOfTwo THEN $
bin(j) = '1' ELSE bin(j) = '0'
ENDFOR
ENDELSE
RETURN, REVERSE(bin)
END
-----------------------------------------------------------
David Fanning, Ph.D.
Fanning Software Consulting
E-Mail: davidf@dfanning.com
Phone: 970-221-0438
Coyote's Guide to IDL Programming: http://www.dfanning.com/
|
|
|