Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

โปรแกรม C# แปลงค่า Byte เป็น Int32


ภาพรวม

ใช้ Convert.ToInt32() แปลง byte เป็น int (Int32) ซึ่งเป็นการแปลงแบบขยายชนิด (widening) ทำได้เสมอโดยไม่สูญเสียข้อมูล

รูปแบบการใช้งาน

byte val = Byte.MaxValue; // 255
int intVal = Convert.ToInt32(val); // 255

ตัวอย่างโค้ดเต็ม

using System;

public class Demo
{
    public static void Main()
    {
        byte val = Byte.MaxValue; // 255
        int intVal = Convert.ToInt32(val);
        Console.WriteLine("Converted byte {0} to Int32 {1} value", val, intVal);
    }
}

ผลลัพธ์

Converted byte 255 to Int32 255 value

วิธีอื่นๆ

  • int intVal = val; - implicit conversion (แปลงโดยนัย) ได้เลย ไม่ต้อง Convert
  • int intVal = (int)val; - explicit cast ก็ได้
  • ทั้งสามวิธีให้ผลลัพธ์เหมือนกัน เนื่องจาก byte → int เป็น widening conversion