How does a computer know that (int x, y) x << y
means shift over y bits? I don't mean the shift part. I mean the y
part. Does the computer shift x by one and subtract one from y until y == 0? If not how does the computer figures out the value of y?
If say y = 10
, then the binary representation is 0b1010
.
The computer can't simply take each bit of 1010
and use it, can it?
I am trying to to this for bit sizes larger than 8. Since the values are not simply stored as arrays of standard integers, the container doesn't represent a value, so overloading the operators <<
and >>
is a bit harder.
Howeve开发者_如何学编程r, counting down from a 100 bit number to 0 is somewhat inefficient, so I'm trying to find a way to make the computer understand a bit array faster.
First off, in C the effects of performing a shift larger than the bit width of the type in question are undefined - in other words, if you have 32 bit ints, x << 33
will result in unreliable results (it need not be zero!).
The exact implementation depends on your hardware. Some embedded processors do indeed perform a loop of single bit shifts; on more powerful CPU architectures such as x86, however, there is a machine instruction to do an arbitrary shift in a single operation, usually using something like a barrel shifter in hardware. The C limitation on the value of the shift oprand comes from different instruction sets handling out-of-range shift values differently; x86 will truncate the shift argument (ie, doing modulo 32 if you're using a 32-bit value), but some other instruction set architectures may have different behavior.
In general, unless you're developing for an embedded processor, you don't need to worry about a single bit shift being expensive.
you're saying you have 2 bit arrays and you're trying to create a shift operator for them? the easiest way to do it would probably be to convert the right one, y
, into an integer and then shift every bit in x
by that amount.....otherwise if you want to operate on it 1 bit at at time it'll be even less efficient. you'll look at the first bit, if its 1, shift once, look at the second bit, if its 1, shift twice...i think you have to deal with it as a whole for it to be efficient.
assuming y
can't fit in an integer...and this is just off the top of my head, but let's assume an int
is only 2 bits, but y
is 0b1111
. then, take the first 2 bits, convert it to an integer (3) and shift x
by that amount. then right-shift y
by 2 (the size of our int), and convert that to an int. this makes 3 again, which you'd have to repeat 4 times (int max + 1) for a total of 12. that, + the 3 we did earlier means we've shifted x
15 times which was the value of y
. you can repeat this process for even larger numbers.
精彩评论