Convert a BitSet to a signed integer using two's complement encoding. - Java java.util

Java examples for java.util:BitSet

Description

Convert a BitSet to a signed integer using two's complement encoding.

Demo Code


//package com.java2s;

import java.util.BitSet;

public class Main {
    /**//from w  w w. j  av  a2 s  .  co  m
     * Convert a BitSet to a signed integer using two's complement encoding. The BitSet is treated as a two's complement encoding binary number.
     *
     * @param b BitSet to convert.
     * @param startBit LSB bit of the integer.
     * @param length Number of bits to read.
     * @return a signed integer number.
     */
    public static int bitSetToSignedInt(BitSet b, int startBit, int length) {
        int signed = -(b.get(startBit + length - 1) ? 1 : 0)
                * (1 << length - 1);
        int bitval = 1;
        for (int i = 0; i < length - 1; i++) {
            if (b.get(startBit + i))
                signed += bitval;
            bitval += bitval;
        }

        return signed;
    }
}

Related Tutorials