Re: Operating with binary numbers
- To: mathgroup at smc.vnet.net
- Subject: [mg59064] Re: Operating with binary numbers
- From: Torsten Coym <torsten.coym at eas.iis.fraunhofer.de>
- Date: Thu, 28 Jul 2005 02:26:08 -0400 (EDT)
- References: <dc77gl$k5p$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Wishmaster wrote: > Hello, > > I found that you can represent binary numbers in Mathematica with this: > > binary = 2^^110110101010111010 > 223930 > > And BaseForm[binary, 10] returns the number in decimal form > 223930 > > I'd like to know if is there some function to test if a given bit of the > binary number is on, and to do operations like "shifting" the binary number. > I looked at the help but can't find anything. > > I use Mathematica 5.0 on Windows XP. > > Thanks. You can find bitwise logical operations such as BitNot, BitAnd, BitOr and BitXor. These can be used to mask the appropriate bits. The following example checks, if the third bit is set: In[66]:= mask3rd = 4; In[65]:= (mask3rd == BitAnd[#1, mask3rd] & ) /@ {4, 8, 10, 12} Out[65]= {True, False, False, True} To shift to the left by n bits multiply the number by 2^n. To shift to the right by n bits multiply by 2^(-n) and get rid of the fractional part either by IntegerPart[], which is save, if you deal only with unsigned integers or Floor[], which should be used when also dealing with negative numbers. Torsten