-3

What does the 'and' instruction do in assembly language? I was told that it checks the bit order of the operands and sets the 1s to true and anything else to false, but I don't know what it actually does or what effect it has on the code.

Peter Cordes
  • 286,368
  • 41
  • 520
  • 731
user548010
  • 11
  • 1
  • 1
  • 1
  • 1
    This should be described in the documentation for any assembler that has an `and` instruction. It does a bit-wise Boolean "and" between two operands. In other words, corresponding bits (bit n in each operand) are anded, in the Boolean operation sense, giving bit n of the result. In Boolean logic, 1 and 1 = 1, but 0 and x (anything else) = 0. Thus, `10111010 and 01101011` results in `00101010`. If you're not familiar with Boolean logic, I suggest starting there and look it up since it's the rudimentary basis of how most electronic computers work. – lurker Dec 04 '18 at 02:13
  • 2
    Does this answer your question? [Understanding the bitwise AND Operator](https://stackoverflow.com/questions/3427585/understanding-the-bitwise-and-operator) – phuclv Mar 06 '21 at 06:11

3 Answers3

3

AND instruction compares the bits in the 2 operands in the following manner:

Bit position 1234 5678
Operand A -- 1101 1001
Operand B -- 1001 0111
             _________
Result ----- 1001 0001

The bits at position 1, 4 and 8 are true in both bytes so the position 1,4 and 8 of the resulting byte will be true. The result will be stored in the first operand.

Serkratos121
  • 31
  • 1
  • 4
1

For 32-bit registers, it does 32 separate/independent boolean and operations, one for each bit position. (true if both inputs are true, otherwise false.)

Like output[4] = a[4] & b[4], where this pseudocode syntax is describing the inputs/output as arrays of bits.

It's exactly the same operation as C's bitwise & or &= operator.

(Not C's && logical-and operator, which checks for !=0).

Peter Cordes
  • 286,368
  • 41
  • 520
  • 731
1

The instruction and performs bit-wise AND operation on its operands. For example the instruction and al, bl should compute the AND operation on the register al and bl (as illustrated by @Serkratos121) and store the result in al register.

It can be used to clear bit(s) off a register. A popular example for this is to convert a lowercase character to uppercase. To convert the m to M. One can write:

mov al, 'm' ; this moves the ascii code of m i.e. 109 to al register

Now, to convert this uppercase, subtract 32 from al. But instead of using sub al, 32d, one can write:

and al, 11011111b ; this clears the 5th bit (LSB is 0th bit)

So, al now contains 77 which is the ascii code for M.

  • If you're counting from zero, you should say "bit #5" to describe the `~(1<<5)` position. [Ordinal numbers](https://en.wikipedia.org/wiki/Ordinal_numeral) like first, second, ..., fifth don't enumerate from zeroth). i.e. bit #5 is the 6th bit. – Peter Cordes May 05 '22 at 08:21