开发者

Working with Byte literals

开发者 https://www.devze.com 2022-12-13 21:16 出处:网络
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):

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 CByted. The second one performs calculations in intege开发者_JAVA技巧rs 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 CBytes, 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?


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().


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消