Byte center transpose reversal, this is an IBM technical interview question for reference.

The original question is as follows:

Given a data of arbitrary byte length (using a Byte as an example), implement the center flip of the data,

which means exchanging the symmetric bits of the data, for example:

1010 1100 -> 0011 0101

1111 1111 -> 1111 1111

0000 0000 -> 0000 0000

1111 0000 -> 0000 1111

The solution is simple, just use bitwise operations to implement the following bit changes, but other

bit situations need to be considered, pay attention to the use of operators, IBM is indeed IBM.

11 - > 11

00 - > 00

10 - > 01

01 - > 10

Below are two implementations of the solution in C and VB.net. VB involves bit conversion and has lower efficiency,

but the algorithm is the same. Also, a recursive algorithm is used here.

VB.net

```
'Global variable to store the data to be converted
Private val As Byte
''' ''' Core algorithm, using recursion to implement byte center transpose
'''
'''
'''
Private Sub fun(ByVal a As Byte)
If a = 0 Then
Exit Sub
End If
'11 - > 11
'00 - > 00
'10 - > 01
'01 - > 10
'The algorithm excludes the cases of 11 and 00, and reverses 01 and 10
'Exclude the case where the result of the AND operation is all 0s
If (val And a) <> (CByte(128 / a) And val) Then
'One of them is 0, the other must be 1, the case of all 1s is naturally excluded
If (val And a) = 0 Or (CByte(128 / a) And val) = 0 Then
'Perform bitwise operation
val = CByte(val Xor (a + CByte(128 / a)))
End If
End If
'Recursive call
fun(a / 2)
End Sub
```

C/C++

//C implementation of byte center transpose

#include #include #define BYTE 8

//#define INTEGER 16

#define LENGTH BYTE

//#define LENGTH INTEGER

//Calculate the argument for parameter passing

#define ARGUMENT pow(2 , (LENGTH / 2 - 1))

//#define ARGUMENT 1 << ( LENGTH/2 -1 )

#define HIGHT 0x80 /*1000 0000*/

//#define HIGHT 0x8000 /*1000 0000 0000 0000*/

unsigned short val = 0;

//unsigned int val = 0;

int fun(int a){

//If a is empty, return

if (0 == a) {

return 0;

}

//'11 - > 11

//'00 - > 00

//'10 - > 01

//'01 - > 10

//'The algorithm excludes the cases of 11 and 00, and reverses 01 and 10

//'Exclude the case where the result of the AND operation is all 0s

if ( (val & a) != ((HIGHT / a) & val) ){

//One of them is 0, the other must be 1, the case of all 1s is naturally excluded

if ( 0 == (val & a) || 0 == ((HIGHT / a) & val) ) {

//Perform bitwise operation

val = val ^ ((HIGHT / a) + a);

}

}

fun(a / 2);

//func(a >> 1);

return 1;

}

int main(int argc , char * args[]) {

//Input

scanf("%d", &val);

//Recursive call

fun(ARGUMENT);

//Output

printf("%d", val);

return 0;

}

Complete code download

http://www.lidaren.com/code/bytecvt/src.zip

VB runtime effect