位操作相当于PERL中的pop函数(删除MSB)
在 Perl 中,是否有一个按位运算符,其作用类似于 >>
,但删除了最高有效位?有点像 >>
运算符有点像 shift()
函数,我正在寻找一个类似于 pop()< 的位运算符/代码>。
110110
将返回 10110
101
将返回 01
最终我想看看二进制形式的数字是否是回文(即 11011、111 或 1010101),因此理想情况下,操作员有办法返回它删除的位。如果运算符不这样做也没关系,因为我可以在数学上这样做,但为了干净的代码,如果它自动返回 MSB 那就太棒了。对于LSB,我愿意
$LSB=$mynum-2*($mynum>>1);
$mynum>>=1;
In Perl, is there a bitwise operator that acts like >>
, but removes the most significant bit? Sort of like how the >>
operator is somewhat like the shift()
function, I'm looking for a bit operator that's like pop()
.
110110
would return 10110
101
would return 01
Ultimately I'm trying to see whether a number in binary form is palindromic (i.e. 11011, 111, or 1010101), so ideally the operator would have a way of returning the bit it removes. It's okay if the operator doesn't, as I could do so mathematically, but in the interest of clean code, it would be awesome if it returned the MSB automatically. For the LSB, I do
$LSB=$mynum-2*($mynum>>1);
$mynum>>=1;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我想不出比将其存储为字符串更简单的方法:
不过你的回文检查只是
I can't think of a simpler way than just storing it as a string:
though then your palindrome check is just
请参阅 如何检查整数的二进制表示是回文吗?
see How to check if the binary representation of an integer is a palindrome?
由于您的值具有可变的位数,因此您需要位字符串或位向量。查看 CPAN 上的 Bit::Vector —— 看来仍然保持活跃。
但正如其他人针对您的问题所建议的那样,处理普通的旧字符串可能会更容易。
Since your values have variable numbers of bits you need a bit string or bit vector. Check out Bit::Vector on CPAN -- it seems to still be active.
But as the others have suggested for your problem it's probably easier for you just to deal with a plain old string.
我不了解 Perl,但在 C/C++ 中你可以这样做:
感谢 Hacker's Delight。
请注意,要查找汇编程序中的最高有效位,您可以在 MSVC _BitScanReverse 和 GCC _builtin_clz 中使用 BSR。然而,据我所知,没有简单的高级(和便携式)运算符。语言的发展速度比 CPU 和编译器慢得多。
I don't know about Perl, but in C/C++ you'd do this like so:
Courtesy of Hacker's Delight.
Note that to find the most significant bit in assembler you could use BSR, in MSVC _BitScanReverse, in GCC _builtin_clz. There are however no simple high-level (and portable) operators that I know of. Languages evolve much slower than CPUs and compilers.