Here you can find the source of booleanToBit(final byte value, final int bitNbr, final boolean state)
byte
.
Parameter | Description |
---|---|
value | The input <code>byte</code> |
bitNbr | The specific bit in the <code>byte</code>, from 0 to 7 |
state | The new state of the specific bit |
byte
with changed bit
public static byte booleanToBit(final byte value, final int bitNbr, final boolean state)
//package com.java2s; /**//from w w w . j av a 2 s.co m * jModuleConnect is an framework for communication and file management on modem * modules. * * This project was inspired by the project TC65SH * by Christoph Vilsmeier: <http://www.vilsmeier-consulting.de/tc65sh.html> * * Copyright (C) 2015 sitec systems GmbH <http://www.sitec-systems.de> * * This file is part of jModuleConnect. * * jModuleConnect is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your option) * any later version. * * jModuleConnect is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with jModuleConnect. If not, see <http://www.gnu.org/licenses/>. */ public class Main { private final static byte[] BIT = new byte[] { (byte) 0x01, (byte) 0x02, (byte) 0x04, (byte) 0x08, (byte) 0x010, (byte) 0x20, (byte) 0x40, (byte) 0x80 }; /** * Sets a specific bit in the input <code>byte</code>. * @param value The input <code>byte</code> * @param bitNbr The specific bit in the <code>byte</code>, from 0 to 7 * @param state The new state of the specific bit * @return The input <code>byte</code> with changed bit * @since 1.0 */ public static byte booleanToBit(final byte value, final int bitNbr, final boolean state) { if (bitNbr < 0 || bitNbr > 7) { throw new IllegalArgumentException("Parameter bitNbr is out of range (0-7)"); } final byte convertedBit = BIT[bitNbr]; byte result = value; if (state) { result |= convertedBit; } else { result &= ~convertedBit; } return result; } }