C语言中使用位域反转位?
如何使用c语言中的按位运算符反转位
例如:
i/p: 10010101
o/p: 10101001
how to reverse the bits using bit wise operators in c language
Eg:
i/p: 10010101
o/p: 10101001
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果它只是 8 位:
或者为了加分:
弄清楚最后一个是如何工作的对读者来说是一项练习;-)
If it's just 8 bits:
Or for bonus points:
figuring out how the last one works is an exercise for the reader ;-)
Knuth 在计算机编程艺术第 4A 卷,按位技巧和技巧。
为了以分而治之的方式反转 32 位数字的位,他使用魔术常量
u0= 1010101010101010, (from -1/(2+1)
u1= 0011001100110011, (from -1/(4+1)
u2= 0000111100001111 , (from -1/(16+1)
u3= 0000000011111111, (from -1/(256+1)
方法归功于 Henry Warren Jr.,黑客们很高兴。16
和 8 位情况留给读者作为练习。
Knuth has a section on Bit reversal in The Art of Computer Programming Vol 4A, bitwise tricks and techniques.
To reverse the bits of a 32 bit number in a divide and conquer fashion he uses magic constants
u0= 1010101010101010, (from -1/(2+1)
u1= 0011001100110011, (from -1/(4+1)
u2= 0000111100001111, (from -1/(16+1)
u3= 0000000011111111, (from -1/(256+1)
Method credited to Henry Warren Jr., Hackers delight.
The 16 and 8 bit cases are left as an exercise to the reader.
好吧,这可能不是最优雅的解决方案,但它是一个解决方案:
在一张纸上测试它,它似乎有效:D
编辑:是的,这确实非常复杂。我不知道为什么,但我想找到一个不接触输入的解决方案,所以这来到了我的脑海
Well, this might not be the most elegant solution but it is a solution:
Tested it on a sheet of paper and it seemed to work :D
Edit: Yeah, this is indeed very complicated. I dunno why, but I wanted to find a solution without touching the input, so this came to my haead