Swap all odd and even bits

Given an unsigned integer N. The task is to swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43(00101011). Here, every even position bit is swapped with adjacent bit on right side(even position bits are highlighted in binary representation of 23), and every odd position bit is swapped with adjacent on left side.

Input:
The first line of input contains T, denoting the number of testcases. Each testcase contains single line.

Output:
For each testcase in new line, print the converted number.

Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100

Example:
Input:
2
23
2

Output:
43
1

Explanation:
Testcase 1:
 BInary representation of the given number; 00010111 after swapping 00101011.

def swapBits(x) : 
    x_str = ''
    while x/2 >0:
        tmp = x % 2
        x_str +=str(tmp) 
        x= int(x/2)
    #print(x_str)
    if len(x_str) %2 ==1:
        x_str += '0'
    #print(x_str)
    tmp_str= ''
    for i in range(int(len(x_str)/2)):
        first = x_str[2*i]
        last = x_str[2*i+1]
        tmp_str += last + first
    #print(tmp_str)
    tmp_str_swap = ''
    for i in range(len(tmp_str)):
        tmp_str_swap += tmp_str[len(tmp_str)-i-1]
    #print(tmp_str_swap)
    return int(tmp_str_swap, 2)
x = 87
print(swapBits(x))
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值