比特位翻转程序

tech2023-08-05  101

一、逆向反转

0x01010011 反转为 0x11001010

#include <stdio.h> unsigned char reserse_value(unsigned char val) { unsigned char reserse_val; int i; for(i=0,reserse_val=0;i<8;i++) { reserse_val = (reserse_val << 1) | (val & 1); val >>= 1; } return reserse_val; } int main(int argc, char *argv[]) { printf("%x\n",reserse_value(0x53));//0x01010011 反转为 0x11001010 return 0; }

二、镜像翻转

0x90 翻转为 0x09

#include <stdio.h> typedef unsigned char uint; uint swapBits(uint x, int i, int j) { uint lo = ((x >> i) & 1); uint hi = ((x >> j) & 1); if (lo ^ hi) { x ^= ((1U << i) | (1U << j)); } return x; } uint reverseXor(uint x) { int n = sizeof(x) * 8; for (int i = 0; i < n/2; i++) { x = swapBits(x, i, n-i-1); } return x; } int main() { printf("%x\n",reverseXor(0x90)); //0x90 翻转为 0x09 return 0; }
最新回复(0)