S
S
synapse_people2016-01-13 10:50:48
Java
synapse_people, 2016-01-13 10:50:48

How does this code work (bitwise shifts)?

In general, there is a code in the JAVA language (the original language is different, but it was ported to JAVA), you need to understand exactly how it works .. The essence is something like this: in order not to use 1 byte each time to transfer a boolean value, it was proposed to use a map of these then subtract them one by one, so 8 boolean values ​​fit into 1 byte (1 bit = 1 boolean). A network packet has approximately the following structure: A map of boolean values, the data itself.
MOMENT NUMBER ONE Modification of positions.
The following code snippet is present in the two methods (getBit/setBit) below. It is clear to me that this is a transformation (shift?) of positions, but I cannot understand why.

int _local2 = (position >> 3);
int _local3 = (7 ^ (position & 7));

Question: What exactly does the first and second line do, and why ?
TIME NUMBER TWO Reading 1 bit (boolean) from the buffer.
boolean getBit(int position) {
*КОПИПАСТ ИЗ МОМЕНТА НОМЕР ОДИН*
*тут ставится позиция буффера в _local2*
return !(((this.map.readByte() & (1 << _local3)) == 0));
}

Question: What does the last line do and why ?
TIME NUMBER THREE Write boolean to buffer.
void setBit(int position, Boolean value) {
*ТУТ ТОЖЕ КОПИПАСТ ИЗ МОМЕНТА НОМЕР ОДИН*
*ТУТ ВЫПОЛНЯЕТСЯ ПРОВЕРКА, ЕСЛИ В БУФФЕРЕ НЕТ МЕСТА ДЛЯ ЗАПИСИ СЛЕДУЮЩЕГО БИТА, ТО АЛЛОЦИРУЕТСЯ 1 БАЙТ*
*тут ставится позиция буффера в _local2*

    if (value) {
      this.map.writeByte((byte) ((this.map.readByte(_local2) | (1 << _local3))));
    } else {
      this.map.writeByte((byte) ((this.map.readByte(_local2) & (0xFF ^ (1 << _local3)))));
    }
  }

Question: What does the last IF block and its branches do, and why ?
Thanks in advance for the detailed answers!
As a solution, I will only note what really helps to simplify the code as much as possible, so that the encoding result is understandable to the remote server (there is NO access to it). Thank you.
AP: I can provide the codec that encodes this card. But the task is to understand exactly how the card itself works, the codec simply receives bytes from this bulaen card and appends its length in the first bits, that's all.
================================================= =======
A simplified version of the code (instead of a buffer - an array of 2 bytes), there is a comparison with BitSet.
private static boolean getBit(byte[] ba, int position) {
    int _local2 = (position >> 3);
    int _local3 = (7 ^ (position & 7));

    byte b = ba[_local2];

    return !((b & (1 << _local3)) == 0);
  }

  private static byte[] setBit(byte[] ba, int position, boolean value) {
    int _local2 = (position >> 3);
    int _local3 = (7 ^ (position & 7));

    if (value) {
      ba[_local2] = (byte) (ba[_local2] | (1 << _local3));
    } else {
      ba[_local2] = (byte) (ba[_local2] & (0xFF ^ (1 << _local3)));
    }

    return ba;
  }

  static String toBinary(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * Byte.SIZE);
    for (int i = 0; i < Byte.SIZE * bytes.length; i++)
      sb.append((bytes[i / Byte.SIZE] << i % Byte.SIZE & 0x80) == 0 ? '0' : '1');
    return sb.toString();
  }

  public static void main(String[] args) {
    
    

    byte[] map = new byte[2];
    map = setBit(map, 0, true);
    map = setBit(map, 1, false);
    map = setBit(map, 2, true);
    map = setBit(map, 3, true);
    map = setBit(map, 4, true);
    map = setBit(map, 14, false);
    map = setBit(map, 15, true);

    System.out.println(toBinary(map));// 1011100000000001 RIGHT!

    System.out.println(getBit(map, 0));// true
    System.out.println(getBit(map, 1));// false
    System.out.println(getBit(map, 2));// true
    System.out.println(getBit(map, 3));// true
    System.out.println(getBit(map, 4));// true
    System.out.println(getBit(map, 14));// false
    System.out.println(getBit(map, 15));// true


BitSet bitSet = new BitSet();
    
    bitSet.set(0, true);
    bitSet.set(1, false);
    bitSet.set(2, true);
    bitSet.set(3, true);
    bitSet.set(4, true);
    bitSet.set(14, false);
    bitSet.set(15, true);
    
    System.out.println(toBinary(bitSet.toByteArray()));//0001110110000000 WTF??
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
R
romy4, 2016-01-13
@romy4

this.map.writeByte((byte) ((this.map.readByte(_local2) & (0xFF ^ (1 << _local3)))));
read the _local2 byte and compare it with the reverse mask depending on the bit at the _local3 position, then write the resulting byte. How can you figure out what it's for?

V
Vitaly, 2016-01-13
@vt4a2h

Someone will figure it out for you ... seriously?
Take a look and understand: https://en.wikipedia.org/wiki/Bitwise_operation . Moreover, you better understand what is being done there and why in terms of business logic.

S
synapse_people, 2016-01-13
@synapse_people

Post updated

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question