Search code examples
javabit-manipulationbit

Bitwise representation into a byte array function


I'm trying to do a memory writing program with bits as part of a CPU simulating program and I don't understand something. I'm making a function to write int value into the memory which is byte double array broken down into segments. Now, I don't understand why the following writeWord function is not working probably, I'll post relevant code as well as the function.

public class RealMemory implements Memory {
    public static final int BYTES_PER_INT = 4;
    public static final int BITS_PER_BYTE = 8;
    private final int segmentSize;
    private final int numberOfSegments; 

    private byte[][] memory;
    
    public RealMemory (int segmentSize, int numberOfSegments) {
        this.segmentSize = segmentSize;
        this.numberOfSegments = numberOfSegments;
        this.memory = new byte[this.numberOfSegments][this.segmentSize];
    }

    private byte[] getSegment(int segment) {
        assert(segment >= 0 && segment < numberOfSegments);
        return memory[segment];
    }

    public void writeWord (int segment, int offset, int value) {
        assert (offset >= 0 && offset < segmentSize - BYTES_PER_INT
             && offset % BYTES_PER_INT == 0);
        byte[] byteword = new byte[BYTES_PER_INT];
        int mask = 1;
        for (int i=offset; i < offset + BYTES_PER_INT; i++) {
            byteword[i-offset] = (byte) (value & mask);
            mask <<= 1;
            getSegment(segment)[i]=byteword[i-offset];
        }
    }
}

I know the way I try to breakdown the value into bits is wrong, I just don't understand bitwise operation needed here fully is my guess. Any help?


Solution

  • Your problem is mask = 1. You don't read bytes, but single bits instead.

    To read bytes, use int mask = (1 << BITS_PER_BYTE) - 1; and mask <<= BITS_PER_BYTE;. Once you masked out the relevant parts you also have to shift it to the right. As Stanislav Bashkyrtsev suggested, this can be done directly on the value instead of shifting the mask.

    int mask = (1 << BITS_PER_BYTE) - 1;
    for (int i=offset; i < offset + BYTES_PER_INT; i++) {
        byteword[i-offset] = (byte) (value & mask);
        value >>= BITS_PER_BYTE;
        getSegment(segment)[i]=byteword[i-offset];
    }