On Apr 19, 1:01 am, "Hak...@[EMAIL PROTECTED]
" <Hak...@[EMAIL PROTECTED]
> wrote:
> Maybe this is just my lack of experience with working with hex, but...
>
> I was asked to produce an M-tree class using unsigned ints in hex to
> traverse through and find nodes. The thing I'm having trouble working
> out is, I was given (on paper) 25E1 & 0010 = 00E0, but when I tried it
> on my computer, I found C++ converting it all to binary and producing
> 0x4 & 0x3 = 100 & 011 = 0.
That's because 0x4 & 0x3 = 0x0.
& is a bitwise and.
25E1 & 0010 = 00E0
First off, I'm not sure if you are clear on this, but the above isn't
hexadecimal in C++. These are double constants in C++. In mathematical
notation these are equivalent with 25 * 10 ^ 1 and 0 * 10 ^ 0
respectively. Generally, you don't want to do bitwise operations with
floating points, which technically aren't standard in C++ (although
there is a fairly standard IEEE specification that most hardware I've
heard of uses). Anyway, I've never heard of a use for doing bitwise
operations on floats, aside from maybe cheazy XOR encryption.
Do you mean?
0x25E1 & 0x0010 == 0x00E0
In that case, the above equation just isn't true. Bellow is the
correct result:
0x25E1 & 0x0010 == 0x0000
>
> Obviously, that's not helpful. How can I take my hex numbers and do
> the & operation?
Bitwise operations are performed on binary bits because there is no
other sort of bit on a computer.
>Or maybe my question is wrong--how can I access the
> n'th digit?
Ah! You want to access the n'th hexadecimal digit! This is not what
bitwise and (&) does. Please look here to see what bitwise operations
do
http://en.wikipedia.org/wiki/Bitwise_operation
Right ****ft (>>) your bits into position (be aware that 4 binary
digits, otherwise known as a nibble, corresponds to one hexadecimal
digit). Once the nibble you want is the least significant in your
number, just chop off everything above that nibble with (num & 0xF).
Then (****fted_num & 0xF) will be the value of your hexadecimal digit.
For instance, say I want digit 2 (counting from zero) of:
int x = 0xABCD;
x = x >> 4 * 2; // now x == 0xAB.
x = x & 0xF; // now x == 0xB.
In general, you will avoid mixups like this if you remember that all
numbers are stored as binary on a computer, and that hex constants
like 0x1234 or decimal constants like 1234 are converted to binary
during compilation. Decimal and hexadecimal don't have a separate type
that bitwise operators work differently on.
--
[ See http://www.gotw.ca/resources/clcm.htm
for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]


|