Here you can find the source of setBit(byte data, int pos, int val)
Parameter | Description |
---|---|
data | the Byte to study |
pos | the bit position to get [0-7] (zero to seven) |
val | the value to set (zero or one) |
public static byte setBit(byte data, int pos, int val)
//package com.java2s; /*//from ww w .java 2s.com * Copyright (C) 2014 Jesse Caulfield * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ public class Main { /** * Set one bit in a byte at the specified position with the specified bit * value. The original data byte is not touched. It is copied, and a new byte * with the bit set is returned. * * @param data the Byte to study * @param pos the bit position to get [0-7] (zero to seven) * @param val the value to set (zero or one) * @return the converted data byte (copy of) */ public static byte setBit(byte data, int pos, int val) { int posBit = pos % 8; return (byte) ((val << (8 - (posBit + 1))) | data); } /** * Set one bit to a bit string at the specified position with the specified * bit value. * * @param data the Byte to study * @param pos the bit position to get [0-7] (zero to seven) * @param val the value to set (zero or one) */ public static void setBit(byte[] data, int pos, int val) { int posByte = pos / 8; int posBit = pos % 8; byte oldByte = data[posByte]; oldByte = (byte) (((0xFF7F >> posBit) & oldByte) & 0x00FF); byte newByte = (byte) ((val << (8 - (posBit + 1))) | oldByte); data[posByte] = newByte; } }