ZetCode

FreeBasic UByte 关键字

最后修改日期:2025 年 6 月 16 日

FreeBasic 的 UByte 关键字表示一个无符号 8 位整数数据类型。它可以存储从 0 到 255 的值。UByte 对于内存高效存储小的正数非常有用。

基本定义

在 FreeBasic 中,UByte 是一种内置数据类型,占用内存正好 1 字节。无符号意味着它只能表示非负值。

UByte 的范围是 0 到 255 (2^8-1)。它通常用于二进制数据、像素值以及内存节省很重要的场景。溢出会在此范围内循环。

声明 UByte 变量

此示例显示了如何声明和初始化 UByte 变量。

ubyte_declare.bas
Dim age As UByte = 25
Dim pixelValue As UByte = 200
Dim defaultUByte As UByte

Print "age: "; age
Print "pixelValue: "; pixelValue
Print "defaultUByte: "; defaultUByte

我们在这里声明了三个 UByte 变量。其中两个已初始化,而一个使用了默认值 0。UByte 变量通过循环自动处理溢出。

UByte 算术运算

UByte 变量支持带有循环的标准算术运算。

ubyte_arithmetic.bas
Dim a As UByte = 200
Dim b As UByte = 100
Dim result As UByte

result = a + b  ' 300 wraps to 44 (300-256)
Print "200 + 100 = "; result

result = a - b  ' 100
Print "200 - 100 = "; result

result = a * 2  ' 400 wraps to 144 (400-256)
Print "200 * 2 = "; result

这演示了带有溢出处理的 UByte 算术。当结果超过 255 时,它们会循环以保持在有效范围内。减法在边界内正常工作。

数组中的 UByte

UByte 数组是存储小型数值数据的内存高效方式。

ubyte_array.bas
Dim grayscale(4) As UByte = {0, 64, 128, 192, 255}

For i As Integer = 0 To 4
    Print "Pixel "; i; ": "; grayscale(i)
Next

这里我们创建了一个 UByte 数组来存储灰度像素值。每个元素仅使用 1 字节内存。这对于内存使用很重要的图像处理非常理想。

带二进制数据的 UByte

UByte 非常适合处理原始二进制数据和文件操作。

ubyte_binary.bas
Dim header(3) As UByte = {&H89, &H50, &H4E, &H47}  ' PNG signature

Print "PNG header bytes:"
For i As Integer = 0 To 3
    Print Hex(header(i)); " ";
Next
Print

此示例将 PNG 文件签名字节存储在 UByte 数组中。十六进制表示法使二进制数据更具可读性。UByte 确保每个值的精确 8 位表示。

UByte 类型转换

FreeBasic 会自动在 UByte 和其他数值类型之间进行转换。

ubyte_conversion.bas
Dim smallNum As UByte = 200
Dim largeNum As Integer = 500

' Implicit conversion
Dim converted As UByte = largeNum  ' Wraps to 244 (500-256)
Print "Converted 500 to UByte: "; converted

' Explicit conversion
converted = CUByte(largeNum Mod 256)
Print "Explicit conversion: "; converted

这显示了到 UByte 的隐式和显式转换。在隐式转换期间,大值会发生循环。CUByte 函数提供了受控的转换。

函数参数中的 UByte

函数可以接受和返回 UByte 值,以实现紧凑的数据处理。

ubyte_function.bas
Function Brighten(pixel As UByte, amount As UByte) As UByte
    Dim result As Integer = pixel + amount
    If result > 255 Then result = 255
    Return result
End Function

Dim original As UByte = 200
Dim brighter As UByte = Brighten(original, 60)

Print "Original: "; original
Print "Brightened: "; brighter

此函数接受 UByte 参数并返回 UByte。它可以提高像素值,同时进行钳位以防止溢出。UByte 参数确保输入值保持在有效范围内。

UByte 按位运算

UByte 变量非常适合与按位运算符一起进行底层操作。

ubyte_bitwise.bas
Dim flags As UByte = &B10101010
Dim mask As UByte = &B00001111

Print "Original: "; Bin(flags, 8)
Print "AND mask: "; Bin(flags And mask, 8)
Print "OR mask:  "; Bin(flags Or mask, 8)
Print "XOR mask: "; Bin(flags Xor mask, 8)
Print "NOT:      "; Bin(Not flags, 8)

这演示了 UByte 值上的按位运算。Bin 函数显示二进制表示。UByte 非常适合标志操作和位掩码操作。

最佳实践

本教程涵盖了 FreeBasic 的 UByte 关键字,并通过实际示例展示了其在不同场景下的用法。

作者

我的名字是 Jan Bodnar,我是一名热情的程序员,拥有丰富的编程经验。自 2007 年以来,我一直在撰写编程文章。到目前为止,我已撰写了 1400 多篇文章和 8 本电子书。我在编程教学方面有十多年的经验。

列出所有 FreeBasic 教程