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.
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.
It seems that this question does not correspond to the subject of the site. Those who voted to close it indicated the following reason:
The essence of the algorithm is simple, despite the apparent complexity of the code:
/* 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; } } } # 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).
Source: https://ru.stackoverflow.com/questions/743744/
All Articles