I have this bit of code that is being converted from vb6 to vb.net. I need to know what LenB is doing in this bit of code.
Dim singleValue As Single 'var for conversion use(4byte -> 1single)' Dim bytes() As Byte Dim valueB() As Byte 'this gets set elsewhere and is redim-d to its size' For n = 0 To CDbl(ItemNumberCombo.Text) - 1 'bytes() -> single' 'UPGRADE_ISSUE: LenB function is not supported.' ReDim bytes(LenB(singleValue) - 1) bytes(3) = valueB(n * 4) bytes(2) = valueB(n * 4 + 1) bytes(1) = valueB(n * 4 + 2) bytes(0) = valueB(n * 4 + 3) 'UPGRADE_ISSUE: LenB function is not supported.' 'UPGRADE_ISSUE: VarPtr function is not supported. ' Call memcpy(VarPtr(singleValue), VarPtr(bytes(0)), LenB(singleValue)) 'display the result' DText(n).Text = VB6.Format(singleValue, '0.000000E+00') 'CStr(singleValue)' If DataSaveCheckBox.CheckState = 1 And FileNameText.Text <> '' Then csvOutput = csvOutput & DText(n).Text & ',' End If Next n
Am I right in thinking that bytes is always ReDim’ed to the same size? By the looks of it 4 elements.
Why then use LenB to ReDim if you could just use a number? And why ReDim in the loop at all?
LenB() returns the length in bytes of a variable. The most common example is for strings, where it returns the size of the string in bytes rather than the number of characters, regardless of character encoding. For other types it returns the size of an object- the size of a single being 4. The reason they would do this is that they wanted the code to survive if a future version of visual basic ever changed the size of a single (never mind hard-coding the number 4 when assigning to the byte array).
When upgrading LenB() to .Net, for strings use
System.Text.Encoding.Unicode.GetBytes()to get an array already populated with your string text bytes. Remember that .Net always uses Unicode for strings internally. If you really need a different encoding there are a number of alternatives in the Encoding namespace. For other types use theBitConverterclass. Either way, don’t go line by line as the newer methods take away a lot of the busy work.Here — I’ll help you out with the conversion some:
(earlier)
(later)
Note that this code also demonstrates a
StringBuilderas a much better way to build your csv data, theAndAlsooperator, the.TryParse()methods,String.IsNullOrEmpty(), and Standard Format Strings, all of which are intended to replace constructs or techniques from vb6.