使用字节文字 [英] Working with Byte literals
问题描述
我正在使用以下函数来加亮颜色值(在我的代码中是lambda,但这不应有区别):
I'm using the following function to brighten up color values (it's a lambda in my code, but that shouldn't make a differende):
Function ReduceDistanceTo255(ByVal i As Byte) As Byte
Return i + (255 - i) \ 2
End Function
由于编译器会解释 255
和 2
作为整数而不是字节,结果为 Integer
。不幸的是,没有字节类型字符,所以我不能只写 255B
或类似的东西。
It won't compile, since the compiler interprets 255
and 2
as integers rather than bytes, making the result of type Integer
. Unfortunately, there is no Byte type character, so I cannot just write 255B
or something like that.
有一些明显的解决方法:
There are a few obvious workarounds to the problem:
Function ReduceDistanceTo255(ByVal i As Byte) As Byte
Return i + (CByte(255) - i) \ CByte(2)
End Function
和
Function ReduceDistanceTo255(ByVal i As Byte) As Byte
Return CByte(i + (255 - i) \ 2)
End Function
和
Function ReduceDistanceTo255(ByVal i As Byte) As Byte
Dim FF As Byte = 255
Dim two As Byte = 2
Return i + (FF - i) \ two
End Function
第一个字符很难看而且很难读,因为每个文字都必须为 CByte
d。第二个执行整数运算,然后将结果转换为Byte,虽然可以,但不如Pure-Byte运算那么优雅。第三种解决方法不需要 CByte
s,但是缺点很明显。
The first one is just plain ugly and hard to read, because every literal needs to be CByte
d. The second one performs calculations in integers and then converts the result to Byte, which is OK, but not as elegant as a pure-Byte operation. The third workaround doesn't require CByte
s, but it's drawbacks are obvious.
我错过了一些(优雅的)第四种选择,它允许我执行仅字节计算而不会与CBools混淆我的公式吗?
Did I miss some (elegant) fourth option which allows me to do Byte-only-math without cluttering my formula with CBools?
推荐答案
Visual Basic语言规范,第2.4.2章:
It is specifically mentioned in the Visual Basic Language Specification, chapter 2.4.2:
Annotation
>不是Byte的类型
字符,因为最大的
自然字符将是B,即十六进制
文字中的
a合法字符。
好吧,我猜是真的。毫无疑问, Octet也被否决了。使用Return CByte(...),它比ToByte()便宜。
Well, that's true I guess. "Octet" got voted down too, no doubt. Use Return CByte(...), it is cheaper than ToByte().
这篇关于使用字节文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!