Finn Eggers
Finn Eggers

Reputation: 945

Java: manipulate bits in a number

I was trying to implement a bit manipulation tool in Java. I do not want to work with the Bitsetclass.

I am working with 64-bit Long values and implemented the following methods:

static final long toggle_bit(long number, int index) {
    return (number ^= (1 << index));
}

static final long set_bit(long number, int index) {
    return (number |= (1 << index));
}

static final long unset_bit(long number, int index) {
    return (number &= ~(1 << index));
}

static final void print_bits(long number) {
    String s = Long.toBinaryString(number);
    String zeros = "0000000000000000000000000000000000000000000000000000000000000000"; //String of 64 zeros
    s = zeros.substring(s.length()) + s;
    System.out.println(s);
}

I think the best way of showing my problem is the result of this code:

>>> print_bits(set_bit(0L, 30));
0000000000000000000000000000000001000000000000000000000000000000

>>> print_bits(set_bit(0L, 31));
1111111111111111111111111111111110000000000000000000000000000000

I assume I am reaching negative values or something like that. I would be very happy if someone could show me a very efficient way of manipulating all 64 bits in a long-number.

Greetings, Finn

Upvotes: 2

Views: 85

Answers (2)

snake_case
snake_case

Reputation: 126

Make index and the1 a long (declare as 1L) so that JVM doesn’t treat it as an integer.

I also have to note that in set_bits, |= (or equals) doesn’t account for when the bit is 1 but the desired value at the bit is 0

Upvotes: 2

Roger Gustavsson
Roger Gustavsson

Reputation: 1709

You are shifting an int value of 1. Try shifting a long value of 1, i.e. 1L << index

Upvotes: 2

Related Questions