右移(分部) - GT; ROUND向零 [英] Right shift (Division) -> ROUND TOWARD ZERO

查看:219
本文介绍了右移(分部) - GT; ROUND向零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样做。

value >> 3;

它总是会向负side.How我圆向零与右移划分?

It is always going toward negative side.How do I round toward zero with right shift division?

推荐答案

请尝试以下操作前pression来代替:

Try the following expression instead:

(value < 0) ? -((-value) >> 3) : value >> 3;

这将迫使负数为正数第一,使其向零舍入,然后更改结果返回至负面。

That will force a negative number to be positive first so that it round towards zero, then changes the result back to negative.

这可能会导致在二进制补码的最小整数问题(而不是一补数或符号/幅度),但你可以在把一个独立的检查,以赶上第一。

This may cause issues for the minimum integer under two's complement notation (not ones' complement or sign/magnitude) but you could put a separate check in to catch that first.

或(和这大概是preferable),你可以只停止的努力八个干脆用右移来划分,而是选择:

Or (and this is probably preferable) you could just stop trying to divide by eight with a right shift altogether, instead choosing:

value = value / 8;

然后让你的编译器选择这样做的最佳途径。你应该编码指定的意图的,而不是试图优化(不必要的,除非你有一个真正的脑死亡的编译器)。

Then let your compiler choose the best way of doing that. You should be coding to specify intent rather than trying to optimise (needlessly, unless you have a truly brain-dead compiler).

这篇关于右移(分部) - GT; ROUND向零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆