对于无符号字节,值太大或太小 [英] Value was either too large or too small for an unsigned byte

查看:727
本文介绍了对于无符号字节,值太大或太小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将int转换为byte,然后使用另一个字节值comap该值。



但它在转换时抛出异常。



以下是代码。



我的尝试:



I am trying to convert an int into byte and then comapare that value with another byte value.

But it is throwing exception while converting.

Below is the code.

What I have tried:

start_index = 0;
int sum = 0;

for (int i = 0; i <= totalLength-2; i++)
{
    sum = (sum + outBuffer.ElementAt(start_index));
    start_index++;
}

int value =Convert.ToByte( outBuffer.ElementAt(totalLength - 1));


byte s = Convert.ToByte(sum); //this lines throws an exception
                              //sum can be upto 5000
                    //so i am trying to convert it into byte because my value is in bytes then i wish to compare them

if (sum==value)
{
    ret_pair.Item2.AddFirst(outBuffer.ElementAt(start_index + 2));
    Convert.ToString("Inside the if block");
}

推荐答案

看看文档: Convert.ToByte方法(Int32)(系统) [ ^ ]:



Just take a look at documentaion: Convert.ToByte Method (Int32) (System)[^] :

OverflowException	

value is less than Byte.MinValue or greater than Byte.MaxValue. 





并且在 MaxValie [ ^ ]:

The value of this constant is 255 (hexadecimal 0xFF).





很高兴知道字节是8位:2 ^ 8 = 256(从0到255)。



Nice to know that the Byte is 8 Bits: 2^8 = 256 (from 0 till 255) .


你不要需要转换为从整数更改为字节;你可以投它:

You don't need Convert to change from an integer to a byte; you can just cast it:
byte s = (byte)sum;

但是......如果你的总和可以达到5000,那么这将不适合一个字节 - 其固定范围为0到255(包括0和255)被定义为8位值,这就是它可以容纳的全部。



你需要查看整个系统并找出你想要一个字节的原因all - 如果值在0到50900范围内,那么如果继续尝试使用字节值来保存它们,整个系统将会失败。

But ... if your sum can be up to 5000, then that will not fit in a byte - which has a fixed range of 0 to 255 inclusive (because it is defined as an 8 bit value, and that is all it can hold).

You need to look at your whole system and work out why you want a byte at all - if the value is in the range 0 to 50900, then your whole system is going to fail if you continue to try an use byte values to hold them.


这篇关于对于无符号字节,值太大或太小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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