For example:
If A -> 00001010(10), B-> 01000001(65), C -> 00011010(26)(Bit Map)
So after swapping specific bits, New A(A') -> 00000000 and
New B(B') -> 01001011
Explanation:
A -> 00001010
C -> 00011010(Swap bits b/w A and B if C's specific bit is 1,
I.e bit 4, 5, 7(direction from left to right)
B -> 01000001
----------------
A' -> 00000000
B' -> 01001011
This is pretty simple. To set A from B only bits MASK:
Clear all bits MASK from A: D = A & ~MASK
Get only bits MASK from B: E = B & MASK
Set required bits to A: RES = D | E
In most of languages it could look like this:
final int a = 0b00001010;
final int b = 0b01000001;
final int c = 0b00011010;
int aa = (a & ~c) | (b & c);
int bb = (b & ~c) | (a & c);
System.out.format("a: %08d\n", new BigInteger(Integer.toBinaryString(aa)));
System.out.format("a: %08d\n", new BigInteger(Integer.toBinaryString(bb)));
P.S. This is only basic bit operations.
Related
This question already has answers here:
What is the idea behind ^= 32, that converts lowercase letters to upper and vice versa?
(10 answers)
Closed 3 years ago.
I've found this code for swapping case, but I'm a bit confused on how it works.
class Main {
private static String swapCase(String s) {
String r = "";
for (char c : s.toCharArray())
r += c ^= 32; // this line
return r;
}
public static void main(String[] args) {
System.out.println(swapCase("Hello"));
}
}
I understood that it loops over each character. But, I can't wrap my head around the line (especially the XOR operator)
r += c ^= 32;
I mean what's the significance of 32? How it swaps the case?
This is how ASCII was set-up.
Letter from a-z have the 6-th bit set to 1; while letters from A-Z have the 6-th bit set to 0.
32 = 100000 // the 6-th bit is set to 1
doing a XOR with an int will invert that 6-th bit.
You could do a little of debugging and see yourself:
for (char c : s.toCharArray()) {
System.out.println(Integer.toBinaryString((int) c));
c ^= 32; // this line
System.out.println(Integer.toBinaryString((int) c));
}
For ASCII encoding 32 is the difference between a lower-case letter and an uppercase letter. It's a power of two, its binary representation is a single 1-bit:
0010 0000.
By applying the XOR assignment operator, you change this bit in the character value. Effectively adding (if the bit is 0 in c) or subtracting (bit is 1 in c) 32.
This will work fine for letters A-Z and a-z but will most likely do nonsense for most other characters in the input.
Let see this table and you will understand why
a = 01100001 A = 01000001
b = 01100010 B = 01000010
c = 01100011 C = 01000011
d = 01100100 D = 01000100
e = 01100101 E = 01000101
f = 01100110 F = 01000110
g = 01100111 G = 01000111
h = 01101000 H = 01001000
i = 01101001 I = 01001001
j = 01101010 J = 01001010
k = 01101011 K = 01001011
l = 01101100 L = 01001100
m = 01101101 M = 01001101
n = 01101110 N = 01001110
o = 01101111 O = 01001111
p = 01110000 P = 01010000
q = 01110001 Q = 01010001
r = 01110010 R = 01010010
s = 01110011 S = 01010011
t = 01110100 T = 01010100
u = 01110101 U = 01010101
v = 01110110 V = 01010110
w = 01110111 W = 01010111
x = 01111000 X = 01011000
y = 01111001 Y = 01011001
z = 01111010 Z = 01011010
The only difference from the upper and lower version is the 5th bit (count from 0). That's why with a simple XOR mask, you can change the case back and forth.
I am working with some low capacity module and I need to compress the data as much as possible. The data will look like this:
DeviceEvent:
1 byte:
2 bits for status (00 each time)
6 bits for rgb color (3 x 2 bits)
2 bytes: number of minutes from now to a certain datetime
I need to create a constructor (preferably 2 constructors) for conversion from/to:
Event:
byte[] color (rgb, colors will get simplified to only 64 available)
some datetime (but I will get the integer for difference in minutes and it will be small enough to fit in two bits)
So basically I need:
byte[3] color <-> 1 byte status and color
int minutes <-> byte[2]
minutes
I will be thankful for any help
I'm not very sure what is your problem, probably this will help:
final byte red = 1; // 01 binary
final byte green = 2; // 10 binary
final byte blue = 3; // 11 binary
final byte finalColor = (byte) ((red & 0x3) << 4) | ((green & 0x3) << 2) | (blue & 0x3);
System.out.println(finalColor);// finalColor is 011011 = 27 decimal
final int minutes = 0x1234; // first byte is 0x12, second byte is 0x34
final byte[] bytes = {(byte) (((minutes) >>> 8) & 0xff), (byte) (minutes & 0xff)};
System.out.println(bytes[0]); // 0x12 = 18 decimal
System.out.println(bytes[1]); // 0x34 = 52 decimal
I am not sure what the second problem is. So I made these two functions that might help you:
public static int convertToInt(int a, int b, int c, int d) {
a = Math.min(a, 255);
b = Math.min(b, 255);
c = Math.min(c, 255);
d = Math.min(d, 255);
return ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | (d & 0xFF);
}
public static int[] extractComponents(int data) {
int a = (data >> 24) & 0xFF;
int b = (data >> 16) & 0xFF;
int c = (data >> 8) & 0xFF;
int d = data & 0xFF;
return new int[] {a, b, c, d};
}
The convertToInt function takes four numbers(that are less than 255) and puts them all in one int.
The extractComponents function does the opposite.
This is an example:
int data = 0xC8E0601B;
int[] dataA = extractComponents(data);
for(int i = 0 ; i < dataA.length; i++) System.out.printf("%x\n", dataA[i]);
System.out.printf("%x\n", convertToInt(dataA[0], dataA[1], dataA[2], dataA[3]));
I have never used bytes in Java before, so I am unfamiliar with the sytnax for manipulating bytes and bits. I searched how to do this task, but I can't find a simple solution.
I have a byte b. b has eight bits. I would like to flip the ith bit of b to its negation (0 -> 1, 1 -> 0). How do I do this?
I think this will work:
byte b = 0; // initial val ...0000000
final int theNumberofTheBitToFlip = 2; // bit to flip
b = (byte) (b ^ (1 << theNumberofTheBitToFlip));
System.out.println(b); // result ...0000100 = 8
b = (byte) (b ^ (1 << theNumberofTheBitToFlip));
System.out.println(b);// result ...0000000 = 8
Try this
int i=3;
b = (byte) (b ^ (1 << i));
I have a binary number and i want to get the decimal value of only the seven bits and not include the 8th bit. How do i go about this in java.
eg. 130 as binary => 10000010, I only need 00000010 =>2 ,ie, change only the most significant bit to 0.
Please help.
Use a bit-mask:
int y = x & 0x7F;
byte b =10;
byte result = (byte) (b & 127);
Under the cover it would be
00001010 //10 in dec
AND 01111111 // our mask ,127 in dec
= 00001010 //10
another example
10000001 //129 in dec
AND 01111111 // our mask ,127 in dec
= 00000001 //1
private static boolean getBit(int b, int p) {
int mask = 1 << 8 - p;
return (b & mask) > 0;
}
private static int setBit(int b, int p) {
int mask = 1 << 8 - p;
return b | mask;
}
private static int unsetBit(int b, int p) {
int mask = 1 << 8 - p;
return b & ~mask;
}
Is there a Python class or module that implements a structure that is similar to the BitSet?
There's nothing in the standard library. Try:
http://pypi.python.org/pypi/bitarray
Have a look at this implementation in Python 3.
The implementation basically makes use of the built-in int type, which is arbitrary precision integer type in Python 3 (where long is the Python 2 equivalent).
#! /usr/bin/env python3
"""
bitset.py
Written by Geremy Condra
Licensed under GPLv3
Released 3 May 2009
This module provides a simple bitset implementation
for Python.
"""
from collections import Sequence
import math
class Bitset(Sequence):
"""A very simple bitset implementation for Python.
Note that, like with normal numbers, the leftmost
index is the MSB, and like normal sequences, that
is 0.
Usage:
>>> b = Bitset(5)
>>> b
Bitset(101)
>>> b[:]
[True, False, True]
>>> b[0] = False
>>> b
Bitset(001)
>>> b << 1
Bitset(010)
>>> b >> 1
Bitset(000)
>>> b & 1
Bitset(001)
>>> b | 2
Bitset(011)
>>> b ^ 6
Bitset(111)
>>> ~b
Bitset(110)
"""
value = 0
length = 0
#classmethod
def from_sequence(cls, seq):
"""Iterates over the sequence to produce a new Bitset.
As in integers, the 0 position represents the LSB.
"""
n = 0
for index, value in enumerate(reversed(seq)):
n += 2**index * bool(int(value))
b = Bitset(n)
return b
def __init__(self, value=0, length=0):
"""Creates a Bitset with the given integer value."""
self.value = value
try: self.length = length or math.floor(math.log(value, 2)) + 1
except Exception: self.length = 0
def __and__(self, other):
b = Bitset(self.value & int(other))
b.length = max((self.length, b.length))
return b
def __or__(self, other):
b = Bitset(self.value | int(other))
b.length = max((self.length, b.length))
return b
def __invert__(self):
b = Bitset(~self.value)
b.length = max((self.length, b.length))
return b
def __xor__(self, value):
b = Bitset(self.value ^ int(value))
b.length = max((self.length, b.length))
return b
def __lshift__(self, value):
b = Bitset(self.value << int(value))
b.length = max((self.length, b.length))
return b
def __rshift__(self, value):
b = Bitset(self.value >> int(value))
b.length = max((self.length, b.length))
return b
def __eq__(self, other):
try:
return self.value == other.value
except Exception:
return self.value == other
def __int__(self):
return self.value
def __str__(self):
s = ""
for i in self[:]:
s += "1" if i else "0"
return s
def __repr__(self):
return "Bitset(%s)" % str(self)
def __getitem__(self, s):
"""Gets the specified position.
Like normal integers, 0 represents the MSB.
"""
try:
start, stop, step = s.indices(len(self))
results = []
for position in range(start, stop, step):
pos = len(self) - position - 1
results.append(bool(self.value & (1 << pos)))
return results
except:
pos = len(self) - s - 1
return bool(self.value & (1 << pos))
def __setitem__(self, s, value):
"""Sets the specified position/s to value.
Like normal integers, 0 represents the MSB.
"""
try:
start, stop, step = s.indices(len(self))
for position in range(start, stop, step):
pos = len(self) - position - 1
if value: self.value |= (1 << pos)
else: self.value &= ~(1 << pos)
maximum_position = max((start + 1, stop, len(self)))
self.length = maximum_position
except:
pos = len(self) - s - 1
if value: self.value |= (1 << pos)
else: self.value &= ~(1 << pos)
if len(self) < pos: self.length = pos
return self
def __iter__(self):
"""Iterates over the values in the bitset."""
for i in self[:]:
yield i
def __len__(self):
"""Returns the length of the bitset."""
return self.length
I wouldn't recommend that in production code but for competitive programming, interview preparation and fun, one should make themselves familiar with bit fiddling.
b = 0 # The empty bitset :)
b |= 1 << i # Set
b & 1 << i # Test
b &= ~(1 << i) # Reset
b ^= 1 << i # Flip i
b = ~b # Flip all
You might like to take a look at a module I wrote called bitstring (full documentation here), although for simple cases that need to be as fast as possible I'd still recommend bitarray.
Some similar questions:
What is the best way to do Bit Field manipulation in Python?
Does Python have a bitfield type?
Python Bitstream implementations
If the number of bits is finite, enum.IntFlag can be used as a bit set.
See https://docs.python.org/3/howto/enum.html#intflag