C#将位旋转到左溢出问题 [英] C# Rotate bits to left overflow issue

查看:63
本文介绍了C#将位旋转到左溢出问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

几天来,我一直在努力使它生效,我已经阅读了一千本指南和人们的疑问,但仍然找不到合适的方法.

I've been trying to get this to work for several days now, i've read a thousand guides and people's questions, but still, i cant find a way to do it properly.

我想做的是将这些位向左旋转,这是一个示例.

What i want to do is to rotate the bits to the left, here's an example.

原始号码= 10000001 = 129 我需要= 00000011 = 3

Original number = 10000001 = 129 What i need = 00000011 = 3

我必须将这些位旋转一定的时间(这取决于用户键入的内容),这是我所做的:

I have to rotate the bits to left a certain ammount of times (it depends on what the user types), here's what i did:

byte b = (byte)129;
byte result = (byte)((byte)b << 1);
Console.WriteLine(result);

Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);

与此有关的问题是,当我尝试使用带有该数字的(<<)运算符时,它会导致错误(OverflowException)(请注意,如果我将一个数字放在第一位的是0,例如:3 = 00000011;它按预期方式工作,结果返回6.

The issue with this it that it causes an error (OverflowException) when i try to use the (<<) operator with that number (note that if i put a number wich first bit is a 0; example: 3 = 00000011; it works as intended and it returns a 6 as a result.

问题是,如果第一位为1,则会给我(OverflorException)错误.我知道这不是旋转的,只是移位,第一位消失了,在字节的末尾弹出了0,然后我可以用OR 000000001操作将其更改为1(如果第一位是1,如果是0,我就把它留在那里.

The problem is, if the first bit is a 1, it gives me the (OverflorException) error. I know this isnt rotating, its just a shifting, the first bit goes away and on the end of the byte a 0 pops up, and i can then change it with an OR 000000001 operation to make it a 1 (if the first bit was a 1, if it was a 0 i just leave it there).

有什么想法吗?预先感谢!

Any ideas? Thanks in advance!

推荐答案

很显然,您正在检查上下文中操作,因此您会收到溢出异常.

You're getting an overflow exception because you're operating in a checked context, apparently.

您可以通过将代码置于未检查的上下文中来解决该问题,或者只是确保您不对大于255的值执行强制转换回byte的操作.例如:

You can get around that by putting the code in an unchecked context - or just by making sure you don't perform the cast back to byte on a value that can be more than 255. For example:

int shifted = b << rotateLeftBits;
int highBits = shifted & 0xff;
int lowBits = shifted >> 8; // Previously high bits, rotated
byte result = (byte) (highBits | lowBits);

这将适用于最大8的旋转大小.对于更大的旋转大小,只需使用rotateLeftBits % 8(如果有时可能想向右旋转,则将其归一化为非负数).

This will work for rotate sizes of up to 8. For greater sizes, just use rotateLeftBits % 8 (and normalize to a non-negative number if you might sometimes want to rotate right).

这篇关于C#将位旋转到左溢出问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆