Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Arithmetic Bit Shift of Double Variable Data Type in C

I am trying to arithmetic bit shift a double data type in C. I was wondering if this is the correct way to do it:

NOTE: firdelay[ ][ ] is declared in main as double firdelay[8][12]

void function1(double firdelay[][12]) {
    int * shiftptr;

    // Cast address of element of 2D matrix (type double) to integer pointer
    *shiftptr = (int *) (&firdelay[0][5]); 

    // Dereference integer pointer and shift right by 12 bits
    *shiftptr >>= 12; 
}
like image 322
Veridian Avatar asked Aug 10 '11 18:08

Veridian


3 Answers

Bitwise shifting a floating point data type will not give you the result you're looking for.

In Simulink, the Shift Arithmetic block only does bit shifting for integer data types. If you feed it a floating point type it divides the input signal by 2^N where N is the number of bits to shift specified in the mask dialog box.

EDIT:
Since you don't have the capability to perform any floating point math your options are:

  • understand the layout of a floating point single precision number, then figure out how to manipulate it bitwise to achieve division.
  • convert whatever algorithm you're porting to use fixed point data types instead of floating point

I'd recommend option 2, it's a whole lot easier than 1

like image 123
Praetorian Avatar answered Nov 18 '22 20:11

Praetorian


Bit-shifting a floating-point data type (reinterpreted as an int) will give you gibberish (take a look at the diagrams of the binary representation here to see why).

If you want to multiply/divide by a power of 2, then you should do that explicitly.

like image 27
Oliver Charlesworth Avatar answered Nov 18 '22 20:11

Oliver Charlesworth


According to the poorly worded and very unclear documentation, it seems that "bit shifting" in Simulink takes two arguments for floating point values and has the effect of multiplying a floating point value by two raised to the difference of the arguments.

You can use ldexp(double_number, bits_to_pseudo_shift) to obtain this behavior. The function ldexp is found in <math.h>.

like image 1
Alexandre C. Avatar answered Nov 18 '22 19:11

Alexandre C.