c#中数值类型的转换

图像处理中,图像经常保存为24位或32位RGB图像,用到的数据类型是byte。c#中的byte数据类型表示的是0-255的整数,当整型和浮点数数值转化为byte类型数值时,遵循一定的规则。
下面是一些数据转为byte类型数值的结果:

从转换结果可以看出对于整型来讲,转为byte型时用的策略是对256取余;对浮点数是先用floor取整,再取余。(并不是说程序在编译器中是这样解释的,只是从结果来分析。)
在图像转化为int整型进行处理后,由于计算机的截断,一般要将数据先加0.5,再显式转化为byte。

代码为:

using System;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("int型转换为byte型数据:");
            for (int i = -2; i < 2; i++)
            {
                 Console.WriteLine("{0} --->  {1}", i, (byte)i);
            }
            for (int i = 254; i < 258; i++)
            {
                Console.WriteLine("{0} --->  {1}", i, (byte)i);
            }
            Console.WriteLine("float型转换为byte型数据:");
            for (int i = -2; i < 2; i++)
            {
                Console.WriteLine("{0} --->  {1}", i+0.5, (byte)i);
            }
            for (int i = 254; i < 258; i++)
            {
                Console.WriteLine("{0} --->  {1}", i+0.5, (byte)i);
            }
            Console.ReadLine();
        }
    }
}
posted @ 2015-12-31 22:31  civftor  阅读(561)  评论(0编辑  收藏  举报