为什么我们需要在Java中使用移位运算符? [英] Why do we need to use shift operators in java?

查看:378
本文介绍了为什么我们需要在Java中使用移位运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  1. 使用Shift运算符而不是使用除法和乘法的目的是什么?

  1. What is the purpose of using Shift operators rather than using division and multiplication?

使用移位运算符还有其他好处吗?

Are there any other benefits of using shift operators?

应该在哪里尝试使用移位运算符?

Where should one try to use the shift operator?

推荐答案

除法和乘法不是真的使用位移运算符.它们是一些想要应用的过时的优化".

Division and multiplication are not really a use of bit-shift operators. They're an outdated 'optimization' some like to apply.

它们是位操作,在整数值内的位级别上工作时完全必要.

They are bit operations, and completely necessary when working at the level of bits within an integer value.

例如,假设我有两个字节,分别是两字节(16位)无符号值的高位和低位字节.假设您需要构建该价值.在Java中,是:

For example, say I have two bytes that are the high-order and low-order bytes of a two-byte (16-bit) unsigned value. Say you need to construct that value. In Java, that's:

int high = ...;
int low = ...;
int twoByteValue = (high << 8) | low;

没有移位运算符,您将无法做到这一点.

You couldn't otherwise do this without a shift operator.

回答您的问题:在需要使用它们的地方使用它们!在别处.

To answer your questions: you use them where you need to use them! and nowhere else.

这篇关于为什么我们需要在Java中使用移位运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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