Working with Byte literals
-
13-09-2019 - |
Question
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
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
and
Function ReduceDistanceTo255(ByVal i As Byte) As Byte
Return CByte(i + (255 - i) \ 2)
End Function
and
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
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.
Did I miss some (elegant) fourth option which allows me to do Byte-only-math without cluttering my formula with CBools?
Solution
It is specifically mentioned in the Visual Basic Language Specification, chapter 2.4.2:
Annotation > There isn’t a type character for Byte because the most natural character would be B, which is a legal character in a hexadecimal literal.
Well, that's true I guess. "Octet" got voted down too, no doubt. Use Return CByte(...), it is cheaper than ToByte().
OTHER TIPS
How about using constants:
Function ReduceDistanceTo255(ByVal i As Byte) As Byte
Const bFF As Byte = 255
Const b02 As Byte = 2
Return i + (bFF - i) \ b02
End Function
no conversion, no casting, no extra variables
How about the easy way:
Imports System.Convert
Function ReduceDistanceTo255(ByVal i As Byte) As Byte
Return ToByte(i + (255 - i) \ 2)
End Function
Edit: I'd prefer this workaround because it would do less casting and it is pretty clear to me what's going on.