简体   繁体   English

Java移位...请解释

[英]Java bit shifting… please explain

I am reviewing some code from an alarm clock project. 我正在查看闹钟项目中的一些代码。 The code uses an integer to store recurring alarm information. 该代码使用整数来存储重复发生的警报信息。 That is, an alarm that occurs say, every MWF. 也就是说,发生警报,​​例如每个MWF。 I understand that integers are simply a series of bytes, and each byte is a series of bits, so you can use that bit information to create an integer that will be unique for every pattern of days of the week. 我知道整数只是一系列字节,每个字节是一系列位,因此您可以使用该位信息来创建一个整数,该整数在一周中的每种模式下都是唯一的。 What I don't understand is the logic in these functions: 我不明白这些功能的逻辑:

// is a given day "set"?
private boolean isSet(int day) {
  return (mDays & (1 << day)) > 0;
}

// set a given day to on or off
public void set(int day, boolean set) {
    if (set) {
        mDays |= (1 << day);
    } else {
        mDays &= ~(1 << day);
    }
}

Could someone please explain what these two function do and how they work? 有人可以解释这两个功能的作用以及如何工作吗?

The isSet Function: isSet函数:

Basically the expression: 基本上表达:

(1 << day)

Means take the number 1: 均值取数字1:

00000001

And shift it over day number of positions to the left. 并将其移至左侧的day数位置。 Such as if day were 3, you'd have: 例如,如果day是3,您将拥有:

00001000

You can use the bitwise & operator to check for common bits. 您可以使用按位&运算符检查公用位。 Such as: 如:

00001000
&
00001000

Will equal 将等于

00001000

However, 然而,

00001000
&
00000001

Will equal 0. Using this, you can check if that particular bit was set , since if you & the number with the bit you're looking for, you're guaranteed to get a number over 0 if that bit matches. 将等于0。利用这一点,您可以检查是否该特定位被设置 ,因为如果你&你正在寻找的比特数,你保证过0,如果该位匹配得到的数字。

The set Function: 设定功能:

The expression: 表达方式:

mDays |= (1 << day);

Is equivalent to: 等效于:

mDays = mDays | (1 << day);

This will basically force the bit expressed with (1 << day) to be true. 这基本上将迫使用(1 << day)表示的位为真。 Say we wanted to flip the 1st bit on: 假设我们想将第一位翻转:

00001000 | 00000001
Equals:
00001001

The expression: 表达方式:

mDays &= ~(1 << day);

Will basically do the inverse of that. 基本上会做相反的事情。 The ~ operator inverts the bits (every 1 becomes a 0, every 0 becomes a 1). ~运算符反转位(每个1变为0,每个0变为1)。 This will ensure that the bit you're setting becomes 0, since anything & 0 is 0 . 这将确保您设置的位变为0,因为& 00 The existing on bits will stay, since the other bits in ~(1 << day) are all 1. 现有的on位将保留,因为~(1 << day)中的其他位均为1。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM