Java/Language Basics/Binary Bit
Содержание
- 1 Binary Digits
- 2 Bit-level unpacking of floating-point data
- 3 Bitwise AND (&)
- 4 Bitwise complement (~): inverts ones and zeroes in a number
- 5 Bitwise Demo
- 6 Bitwise OR (|)
- 7 Bitwise XOR (^)
- 8 Convert a number to negative and back
- 9 Converting Between a BitSet and a Byte Array
- 10 Left shift (<<)
- 11 Performing Bitwise Operations on a Bit Vector
- 12 Returns a byte array of at least length 1
- 13 Shift to the left
- 14 Signed shift to the right
- 15 Unsigned shift to the right
- 16 Using the bitwise operators
- 17 Utility for byte swapping of all java data types
Binary Digits
/**
* Template for standalone, line-mode main program.
* @author Ian F. Darwin, http://www.darwinsys.ru/
* @version $Id: BinaryDigits.java,v 1.3 2004/02/09 03:33:56 ian Exp $
*/
public class BinaryDigits {
public static void main(String[] argv) {
//+
String bin = "101010";
System.out.println(bin + " as an integer is " + Integer.valueOf(bin, 2));
int i = 42;
System.out.println(i + " as binary digits (bits) is " +
Integer.toBinaryString(i));
//-
}
}
Bit-level unpacking of floating-point data
/*
Java Programming for Engineers
Julio Sanchez
Maria P. Canton
ISBN: 0849308100
Publisher: CRC Press
*/
// Java for Engineers
//Filename: BitOps
//Reference: Chapter 24
//Description:
// Bit-level unpacking of floating-pioint data
//Requires:
// Keyin class in current directory
class BitOps {
public static void main(String[] args) {
// Definition of bit field masks for double
final long SIGN = 0x8000000000000000L;
final long EXPN = 0x7ff0000000000000L;
final long SGNF = 0x000fffffffffffffL;
final long BIT1 = 0x8000000000000000L;
// Storage for bit fields
long s; // Sign
long e; // Exponent field
long m; // Significand (mantissa) field
String eS; // For conversions
double num;
long binVal;
long t;
// Get user input
num = 3.4d;
binVal = Double.doubleToRawLongBits(num);
// Display hex bits
System.out.println("As long = " + Long.toHexString(binVal));
// Display bit fields of double format
s = binVal & SIGN;
if (s != 0)
System.out.println("Sign = -");
else
System.out.println("Sign = +");
// Mask out exponent field
e = (binVal & EXPN);
eS = Long.toHexString(e);
System.out.println("Exponent = " + eS);
// Mask out significand field
m = (binVal & SGNF);
eS = Long.toHexString(m);
System.out.println("Significand = " + eS);
System.out.println("\nFields in binary");
if (s != 0)
System.out.println("Sign bit = 1");
else
System.out.println("Sign bit = 0");
// Display binary exponent
// Eliminate sign bit
e = e << 1;
System.out.print("Exponent = ");
for (int k = 0; k < 11; k++) {
t = e & BIT1;
// System.out.println(Long.toHexString(t));
if (t != 0)
System.out.print("1");
else
System.out.print("0");
e = e << 1;
}
System.out.println("\n |-11 bits-|");
// Display binary significand
// Eliminate exponent and sign bits
m = m << 12;
System.out.print("Significand = 1.");
for (int j = 0; j < 51; j++) {
t = m & BIT1;
if (t != 0)
System.out.print("1");
else
System.out.print("0");
m = m << 1;
}
System.out.println("\n ^ |");
System.out.println("implicit bit -| | ----- 52 bits -->");
}
}
Bitwise AND (&)
public class Main {
public static void main(String[] a) {
System.out.println(9 & 7);
}
}
//1
Bitwise complement (~): inverts ones and zeroes in a number
public class Main {
public static void main(String[] a) {
int i = 1;
System.out.println(i);
int j = ~i + 1;
System.out.println(j);
i = ~j + 1;
System.out.println(i);
}
}
/*
1
-1
1
*/
Bitwise Demo
/* From http://java.sun.ru/docs/books/tutorial/index.html */
/*
* Copyright (c) 2006 Sun Microsystems, Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* -Redistribution of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* -Redistribution in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of Sun Microsystems, Inc. or the names of contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* This software is provided "AS IS," without a warranty of any kind. ALL
* EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING
* ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN MIDROSYSTEMS, INC. ("SUN")
* AND ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE
* AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR ITS
* DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS BE LIABLE FOR ANY LOST
* REVENUE, PROFIT OR DATA, OR FOR DIRECT, INDIRECT, SPECIAL, CONSEQUENTIAL,
* INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER CAUSED AND REGARDLESS OF THE THEORY
* OF LIABILITY, ARISING OUT OF THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF SUN HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
* You acknowledge that this software is not designed, licensed or intended
* for use in the design, construction, operation or maintenance of any
* nuclear facility.
*/
public class BitwiseDemo {
static final int VISIBLE = 1;
static final int DRAGGABLE = 2;
static final int SELECTABLE = 4;
static final int EDITABLE = 8;
public static void main(String[] args)
{
int flags = 0;
flags = flags | VISIBLE;
flags = flags | DRAGGABLE;
if ((flags & VISIBLE) == VISIBLE) {
if ((flags & DRAGGABLE) == DRAGGABLE) {
System.out.println("Flags are Visible and Draggable.");
}
}
flags = flags | EDITABLE;
if ((flags & EDITABLE) == EDITABLE) {
System.out.println("Flags are now also Editable.");
}
}
}
Bitwise OR (|)
public class Main {
public static void main(String[] a) {
System.out.println(19 | 7);
}
}
//23
Bitwise XOR (^)
public class Main {
public static void main(String[] a) {
System.out.println(9 ^ 7);
}
}
//14
Convert a number to negative and back
public class Main {
public static void main(String[] a) {
int i = 1;
System.out.println(i);
int j = ~i + 1;
System.out.println(j);
i = ~j + 1;
System.out.println(i);
}
}
/*
1
-1
1
*/
Converting Between a BitSet and a Byte Array
import java.util.BitSet;
public class Main {
public static void main(String[] argv) throws Exception {
System.out.println(fromByteArray(new byte[]{1,2,3}));
}
// Returns a bitset containing the values in bytes.
public static BitSet fromByteArray(byte[] bytes) {
BitSet bits = new BitSet();
for (int i = 0; i < bytes.length * 8; i++) {
if ((bytes[bytes.length - i / 8 - 1] & (1 << (i % 8))) > 0) {
bits.set(i);
}
}
return bits;
}
}
//{0, 1, 9, 16}
Left shift (<<)
public class Main {
public static void main(String[] a) {
System.out.println(9 << 7);
}
}
//1152
Performing Bitwise Operations on a Bit Vector
import java.util.BitSet;
public class Main {
public static void main(String[] argv) throws Exception {
// Create the bitset
BitSet bits = new BitSet();
// Set a bit on
bits.set(2);
// Retrieving the value of a bit
boolean b = bits.get(0);
b = bits.get(2);
// Clear a bit
bits.clear(1);
// Setting a range of bits
BitSet bits2 = new BitSet();
bits2.set(1, 4);
// And"ing two bitsets
bits.and(bits2);
// Xor"ing two bitsets
bits.xor(bits2);
// Flip all bits in the bitset
bits.flip(0, bits.length());
// Andnot"ing two bitsets
bits.andNot(bits2);
// Or"ing two bitsets
bits.or(bits2);
}
}
Returns a byte array of at least length 1
import java.util.BitSet;
public class Main {
public static void main(String[] argv) throws Exception {
BitSet bitset = new BitSet();
bitset.set(1);
System.out.println(toByteArray(bitset));
}
public static byte[] toByteArray(BitSet bits) {
byte[] bytes = new byte[bits.length() / 8 + 1];
for (int i = 0; i < bits.length(); i++) {
if (bits.get(i)) {
bytes[bytes.length - i / 8 - 1] |= 1 << (i % 8);
}
}
return bytes;
}
}
Shift to the left
public class Main {
public static void main(String[] args) {
byte b = 11;
System.out.println(b << 1);
}
}
Signed shift to the right
public class Main {
public static void main(String[] argv) throws Exception {
byte b = 11;
System.out.println(b >> 1);
}
}
Unsigned shift to the right
public class Main {
public static void main(String[] argv) throws Exception {
byte b = 11;
System.out.println(b >>> 1);
}
}
Using the bitwise operators
//: c03:BitManipulation.java
// Using the bitwise operators.
// From "Thinking in Java, 3rd ed." (c) Bruce Eckel 2002
// www.BruceEckel.ru. See copyright notice in CopyRight.txt.
import java.util.*;
public class BitManipulation {
public static void main(String[] args) {
Random rand = new Random();
int i = rand.nextInt();
int j = rand.nextInt();
printBinaryInt("-1", -1);
printBinaryInt("+1", +1);
int maxpos = 2147483647;
printBinaryInt("maxpos", maxpos);
int maxneg = -2147483648;
printBinaryInt("maxneg", maxneg);
printBinaryInt("i", i);
printBinaryInt("~i", ~i);
printBinaryInt("-i", -i);
printBinaryInt("j", j);
printBinaryInt("i & j", i & j);
printBinaryInt("i | j", i | j);
printBinaryInt("i ^ j", i ^ j);
printBinaryInt("i << 5", i << 5);
printBinaryInt("i >> 5", i >> 5);
printBinaryInt("(~i) >> 5", (~i) >> 5);
printBinaryInt("i >>> 5", i >>> 5);
printBinaryInt("(~i) >>> 5", (~i) >>> 5);
long l = rand.nextLong();
long m = rand.nextLong();
printBinaryLong("-1L", -1L);
printBinaryLong("+1L", +1L);
long ll = 9223372036854775807L;
printBinaryLong("maxpos", ll);
long lln = -9223372036854775808L;
printBinaryLong("maxneg", lln);
printBinaryLong("l", l);
printBinaryLong("~l", ~l);
printBinaryLong("-l", -l);
printBinaryLong("m", m);
printBinaryLong("l & m", l & m);
printBinaryLong("l | m", l | m);
printBinaryLong("l ^ m", l ^ m);
printBinaryLong("l << 5", l << 5);
printBinaryLong("l >> 5", l >> 5);
printBinaryLong("(~l) >> 5", (~l) >> 5);
printBinaryLong("l >>> 5", l >>> 5);
printBinaryLong("(~l) >>> 5", (~l) >>> 5);
}
static void printBinaryInt(String s, int i) {
System.out.println(
s + ", int: " + i + ", binary: ");
System.out.print(" ");
for(int j = 31; j >= 0; j--)
if(((1 << j) & i) != 0)
System.out.print("1");
else
System.out.print("0");
System.out.println();
}
static void printBinaryLong(String s, long l) {
System.out.println(
s + ", long: " + l + ", binary: ");
System.out.print(" ");
for(int i = 63; i >= 0; i--)
if(((1L << i) & l) != 0)
System.out.print("1");
else
System.out.print("0");
System.out.println();
}
} ///:~
Utility for byte swapping of all java data types
/*
* (C) 2004 - Geotechnical Software Services
*
* This code 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 2.1 of the License, or (at your option) any later version.
*
* This code 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 this program; if not, write to the Free
* Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
* MA 02111-1307, USA.
*/
//package no.geosoft.cc.util;
/**
* Utility class for doing byte swapping (i.e. conversion between
* little-endian and big-endian representations) of different data types.
* Byte swapping is typically used when data is read from a stream
* delivered by a system of different endian type as the present one.
*
* @author
*/
public class ByteSwapper
{
/**
* Byte swap a single short value.
*
* @param value Value to byte swap.
* @return Byte swapped representation.
*/
public static short swap (short value)
{
int b1 = value & 0xff;
int b2 = (value >> 8) & 0xff;
return (short) (b1 << 8 | b2 << 0);
}
/**
* Byte swap a single int value.
*
* @param value Value to byte swap.
* @return Byte swapped representation.
*/
public static int swap (int value)
{
int b1 = (value >> 0) & 0xff;
int b2 = (value >> 8) & 0xff;
int b3 = (value >> 16) & 0xff;
int b4 = (value >> 24) & 0xff;
return b1 << 24 | b2 << 16 | b3 << 8 | b4 << 0;
}
/**
* Byte swap a single long value.
*
* @param value Value to byte swap.
* @return Byte swapped representation.
*/
public static long swap (long value)
{
long b1 = (value >> 0) & 0xff;
long b2 = (value >> 8) & 0xff;
long b3 = (value >> 16) & 0xff;
long b4 = (value >> 24) & 0xff;
long b5 = (value >> 32) & 0xff;
long b6 = (value >> 40) & 0xff;
long b7 = (value >> 48) & 0xff;
long b8 = (value >> 56) & 0xff;
return b1 << 56 | b2 << 48 | b3 << 40 | b4 << 32 |
b5 << 24 | b6 << 16 | b7 << 8 | b8 << 0;
}
/**
* Byte swap a single float value.
*
* @param value Value to byte swap.
* @return Byte swapped representation.
*/
public static float swap (float value)
{
int intValue = Float.floatToIntBits (value);
intValue = swap (intValue);
return Float.intBitsToFloat (intValue);
}
/**
* Byte swap a single double value.
*
* @param value Value to byte swap.
* @return Byte swapped representation.
*/
public static double swap (double value)
{
long longValue = Double.doubleToLongBits (value);
longValue = swap (longValue);
return Double.longBitsToDouble (longValue);
}
/**
* Byte swap an array of shorts. The result of the swapping
* is put back into the specified array.
*
* @param array Array of values to swap
*/
public static void swap (short[] array)
{
for (int i = 0; i < array.length; i++)
array[i] = swap (array[i]);
}
/**
* Byte swap an array of ints. The result of the swapping
* is put back into the specified array.
*
* @param array Array of values to swap
*/
public static void swap (int[] array)
{
for (int i = 0; i < array.length; i++)
array[i] = swap (array[i]);
}
/**
* Byte swap an array of longs. The result of the swapping
* is put back into the specified array.
*
* @param array Array of values to swap
*/
public static void swap (long[] array)
{
for (int i = 0; i < array.length; i++)
array[i] = swap (array[i]);
}
/**
* Byte swap an array of floats. The result of the swapping
* is put back into the specified array.
*
* @param array Array of values to swap
*/
public static void swap (float[] array)
{
for (int i = 0; i < array.length; i++)
array[i] = swap (array[i]);
}
/**
* Byte swap an array of doubles. The result of the swapping
* is put back into the specified array.
*
* @param array Array of values to swap
*/
public static void swap (double[] array)
{
for (int i = 0; i < array.length; i++)
array[i] = swap (array[i]);
}
}