Assembly Language for Beginners

(Jeff_L) #1

1.22. MANIPULATING SPECIFIC BIT(S)


1.22.3 Shifts


Bit shifts in C/C++ are implemented using≪and≫operators. The x86ISAhas the SHL (SHift Left) and
SHR (SHift Right) instructions for this. Shift instructions are often used in division and multiplications by
powers of two: 2 n(e.g., 1, 2, 4, 8, etc.):1.18.1 on page 213,1.18.2 on page 217.


Shifting operations are also so important because they are often used for specific bit isolation or for
constructing a value of several scattered bits.


1.22.4 Setting and clearing specific bits: FPUexample


Here is how bits are located in thefloattype in IEEE 754 form:


3031 2322 0

S exponent mantissa or fraction

( S—sign )

The sign of number is in theMSB^150. Will it be possible to change the sign of a floating point number
without any FPU instructions?


#include <stdio.h>


float my_abs (float i)
{
unsigned int tmp=((unsigned int)&i) & 0x7FFFFFFF;
return (float)&tmp;
};


float set_sign (float i)
{
unsigned int tmp=((unsigned int)&i) | 0x80000000;
return (float)&tmp;
};


float negate (float i)
{
unsigned int tmp=((unsigned int)&i) ^ 0x80000000;
return (float)&tmp;
};


int main()
{
printf ("my_abs():\n");
printf ("%f\n", my_abs (123.456));
printf ("%f\n", my_abs (-456.123));
printf ("set_sign():\n");
printf ("%f\n", set_sign (123.456));
printf ("%f\n", set_sign (-456.123));
printf ("negate():\n");
printf ("%f\n", negate (123.456));
printf ("%f\n", negate (-456.123));
};


We need this trickery in C/C++ to copy to/fromfloatvalue without actual conversion. So there are three
functions: my_abs() resetsMSB;set_sign()setsMSBand negate() flips it.


XORcan be used to flip a bit:2.6 on page 461.


x86


The code is pretty straightforward:


(^150) Most Significant Bit

Free download pdf