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

Convert.ToByte Method ใน C#: แปลงเป็น 8-bit Unsigned Integer

เมธอด Convert.ToByte() แปลงค่าที่ระบุเป็น byte (8-bit Unsigned Integer) ช่วงค่า 0 ถึง 255

ตัวอย่าง: แปลงจาก Char Array

using System;

public class Demo
{
    public static void Main()
    {
        char[] charVal = { 'p', 'q', 'r', 's' };
        
        foreach (char c in charVal)
        {
            byte byteVal = Convert.ToByte(c);
            Console.WriteLine($"{c} is converted to = {byteVal}");
        }
    }
}

ผลลัพธ์

p is converted to = 112
q is converted to = 113
r is converted to = 114
s is converted to = 115

Overloads และตัวอย่างเพิ่มเติม

// จาก String
byte b1 = Convert.ToByte("200"); // 200

// จาก int
byte b2 = Convert.ToByte(150); // 150

// จาก long
byte b3 = Convert.ToByte(300L); // OverflowException! > 255

// จาก double
byte b4 = Convert.ToByte(127.9); // 127 (Truncate)

// จาก object
object obj = "255";
byte b5 = Convert.ToByte(obj); // 255

// Base64 String -> Byte Array (ไม่ใช่ ToByte)
string base64 = "SGVsbG8=";
byte[] bytes = Convert.FromBase64String(base64); // [72, 101, 108, 108, 111]

ข้อยกเว้น

  • OverflowException - ค่าน้อยกว่า 0 หรือ มากกว่า 255
  • FormatException - String ไม่ใช่ตัวเลข

การแปลงปลอดภัย

// TryParse
if (byte.TryParse("200", out byte val))
    Console.WriteLine(val);

// Pattern Matching
if (input is string s && byte.TryParse(s, out var b))
    Console.WriteLine(b);

Byte vs SByte

TypeRangeCLS-Compliant
byte (System.Byte)0 to 255Yes
sbyte (System.SByte)-128 to 127No

ใช้ byte สำหรับ: Binary Data, File I/O, Network Packets, Image Processing, Cryptography