Java Bits Convert to bitfieldToString(String[] statenames, int value)

Here you can find the source of bitfieldToString(String[] statenames, int value)

Description

Given a bitfield value @p value, and an array that names each bit position, return a comma-separated string that names each bit position that is set in @p value.

License

Open Source License

Declaration

public static String bitfieldToString(String[] statenames, int value) 

Method Source Code

//package com.java2s;

public class Main {
    /**/*  w  w  w .ja  v a 2s. com*/
    * Given a bitfield value @p value, and an array that names
    * each bit position, return a comma-separated string that
    * names each bit position that is set in @p value.
    *
    * Test cases:
    *   - value 0, a few random ones, -1 (0xffffffffffffffff), MAXINT.
    *   - null names, 0-length names, names contains nulls,
    *   - names contains empty strings, names too short for value,
    *   - names too long.
    */
    public static String bitfieldToString(String[] statenames, int value) {
        if ((value == 0) || (statenames == null) || (statenames.length == 0)) {
            return "";
        }
        StringBuilder b = new StringBuilder();
        for (int statebit = 0; statebit < statenames.length; statebit++) {
            int statebitvalue = 1 << statebit;
            if ((value & statebitvalue) != 0) {
                // ASSERT: statebit < statenames.length
                // TODO: handle null strings
                b.append(statenames[statebit]);
                // TODO: make this bit-twiddling, may fail with negative value
                value -= statebitvalue;
                if (value != 0) {
                    b.append(", ");
                }
            }
        }
        return b.toString();
    }
}

Related

  1. bitboardToString(final long l)
  2. bitboardToString(long bitboard)
  3. bitch(Throwable t)
  4. bitFieldToIndexArray(long bitfield)
  5. bitFieldToString(boolean[] bits)
  6. bitFlagByteLength(final int nbits)
  7. bitHistogram(int[] data)
  8. bitMap(final boolean v1, final boolean v2, final boolean v3, final boolean v4, final boolean v5, final boolean v6, final boolean v7, final boolean v8)
  9. bitmap64(byte... table)