Working with Byte literals

只谈情不闲聊 提交于 2019-12-24 12:13:03

问题


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 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 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?


回答1:


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




回答2:


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




回答3:


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.



来源:https://stackoverflow.com/questions/1859681/working-with-byte-literals

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!