码迷,mamicode.com
首页 > 其他好文 > 详细

左右翻转二进制数==》繁琐与精简

时间:2015-10-17 07:09:47      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:左右翻转二进制数==》思想的稍微不同引起的爆炸效应

实现:

//00000000000000000000000000011001

//10011000000000000000000000000000

这种翻转

方法一和方法二思路大致一样,可以方法二却十分麻烦。

方法一(简单)

#include<stdio.h>
#include<math.h>
unsigned int  reverse_bit(unsigned int value)
{
        int i = 0;
        unsigned int Value ;
        unsigned int num = 0;
for (i = 1; i <= 32; i++)
{
        Value = value;
        int b = ((value%2)&&1);
        num = num + b*(pow(2, (32 - i)));
        value=Value >> 1;
}
return num;
}
int main()
{
        unsigned int number = 25;
        printf("%u", reverse_bit(number));
}

方法二(思想简单但写的十分复杂,我都不知道我咋想出来的)
#include<stdio.h>
#include<math.h>
unsigned int zhishu(int x, int cishu)
{
	unsigned int num = pow(2, cishu);
	return (x*num);
}
int num_sing(int max)
{
	if (max % 2 == 0)
	{
		return 0;
	}
	else
	{
		return 1;
	}
}
unsigned int fzsign(unsigned int a)
{
	unsigned int num = 0;
	int sing = num_sing(a);
	int cishu = 0 + sing;
	unsigned int tmp = a;
	unsigned int b = 0;
	while (a != sing)
	{
		a = a / 2;
		cishu++;
	}
	/*printf("%d\n", cishu);*/
	int sings = num_sing(tmp);
	int tmp2 = cishu;
	cishu = cishu - 1;
	while (tmp != sings)
	{
		b = tmp % 2;
		tmp = tmp / 2;
		num = num + zhishu(b, cishu);
		cishu--;
	}
	num = num + sings;
	num = num << (32 - tmp2);
	return num;

}
int main()
{
	unsigned int a = 25;
	unsigned int num=fzsign(a);
		printf("%u", num);


}
     法二像不像大杂烩!!!


本文出自 “痕迹” 博客,请务必保留此出处http://wpfbcr.blog.51cto.com/10696766/1703666

左右翻转二进制数==》繁琐与精简

标签:左右翻转二进制数==》思想的稍微不同引起的爆炸效应

原文地址:http://wpfbcr.blog.51cto.com/10696766/1703666

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!