The task:

Implement the Reverse function, which accepts an array of bytes as input, performs a bit reverse of each byte in the array and displays the result on the screen.

I do not understand how to solve.

Closed due to the fact that off-topic by the participants Kromster , cheops , Alexander Petrov , Abyx , Kirill Malyshev Nov 17 '17 at 19:17 .

It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:

  • " Learning tasks are allowed as questions only on the condition that you tried to solve them yourself before asking a question . Please edit the question and indicate what caused you difficulties in solving the problem. For example, give the code you wrote, trying to solve the problem "- Kromster, cheops, Alexander Petrov, Abyx, Kirill Malyshev
If the question can be reformulated according to the rules set out in the certificate , edit it .

  • one
    Expand the byte - as a last resort, you can start a table with 256 elements. - KoVadim
  • @KoVadim What's extreme about him? great approach ... - Akina
  • one
    Is bit reverse the replacement of 0 by 1 and 1 by 0? Then byte = byte ^ 0xFF to help you - Vladimir Martyanov
  • No, this is the first bit last and vice versa - KoVadim

2 answers 2

The essence of the algorithm is simple, despite the apparent complexity of the code:

  1. changing adjacent byte bits
  2. change adjacent pairs of bits
  3. change adjacent fours bits

/* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) throws java.lang.Exception { byte[] arr = {5, 10, 100, -10}; revers(arr); } public static void revers (byte[] args) { for(int i=0; i<args.length; i++) { int tmp = (int)args[i]; tmp = ((tmp & 0x55) << 1) | ((tmp >> 1) & 0x55); tmp = ((tmp & 0x33) << 2) | ((tmp >> 2) & 0x33); tmp = ((tmp & 0x0F) << 4) | ((tmp >> 4) & 0x0F); System.out.format("# %d Byte revers to %d\n",args[i],(byte)tmp); args[i] = (byte)tmp; } } } 

IDEONE

 # 5 Byte revers to -96 # 10 Byte revers to 80 # 100 Byte revers to 38 # -10 Byte revers to 111 

On ECMAScript (JS) it is possible so, through the lines .. for example, suppose that we have a Byte without a sign

// convert byte to binary string // left normalization with zeros and take the last 8 characters of the string
// divide the string into an array of characters 0,1
// reverse array
// "glue" the array back into the string
// convert it to a binary number

 var arr = [5, 10, 255, 254]; console.log(invert(arr)); function invert(arr) { for (i in arr) { var elemstring = ("0000000" + arr[i].toString(2)).slice(-8); arr[i] = parseInt(elemstring.split('').reverse().join(''), 2); } return arr; } 

     public int reverse(int number){ return ~number; } 

    For example, if you send 10 ( 1010 in binary), it returns -11 ( 1111 1111 1111 1111 1111 1111 1111 0101 in binary).

    A source