Quantcast
Channel: User Alex Lop. - Stack Overflow
Viewing all articles
Browse latest Browse all 39

Answer by Alex Lop. for Which kind of signed integer division corresponds to bit shift?

$
0
0

In case arithmetic shift right is performed, floor by power of 2 is the best suitable operation which matches signed integer shift right (rounding toward -inf).

Note that shift right of signed integer is implementation defined. It may be either arithmetic shift right (implemented by most of the well known compilers) or logical shift right. More about the difference between those two operations can be found here.

Example with arithmetic shift right: https://godbolt.org/z/zhhfbc

#include <stdio.h>#include <math.h>int main(void){    int val1 = 7;    int val2 = -7;    printf("Value1 = %.1lf\n", floor(val1/2.0));    printf("Value2 = %.1lf\n", floor(val2/2.0));    printf("Value1 = %d\n", val1 >> 1);    printf("Value2 = %d\n", val2 >> 1);      return 0;}

And the output is:

Value1 = 3.0Value2 = -4.0Value1 = 3Value2 = -4

Viewing all articles
Browse latest Browse all 39

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>