If I have two variables containing binary values, how do I append them together as one binary value? For example, if I used WMI to read the registry of two REG_BINARY value, I then want to be able to concatenate the values.
VBScript complains of a type mismatch when you try to join with the '&' operator.
REG_BINARY value will be returned as an array of bytes. VBScript may reference an array of bytes in a variable and it may pass this array of bytes either as a variant to another function or as a reference to array of bytes. However VBScript itself can do nothing with the array.
You are going to need some other component to do some from of concatenation:-
Function ConcatByteArrays(ra, rb)
Dim oStream : Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1 'Binary'
oStream.Write ra
oStream.Write rb
oStream.Position = 0
ConcatByteArrays = oStream.Read(LenB(ra) + LenB(rb))
oStream.Close
End Function
In the above code I'm using the ADODB.Stream object which is ubiquitous on currently supported platforms.
If you actually had multiple arrays that you want to concatenate then you could use the following class:-
Class ByteArrayBuilder
Private moStream
Sub Class_Initialize()
Set moStream = CreateObject("ADODB.Stream")
moStream.Open
moStream.Type = 1
End Sub
Public Sub Append(rabyt)
moStream.Write rabyt
End Sub
Public Property Get Length
Length = moStream.Size
End Property
Public Function GetArray()
moStream.Position = 0
GetArray = moStream.Read(moStream.Size)
End Function
Sub Class_Terminate()
moStream.Close
End Sub
End Class
Call append as many times as you have arrays and retrieve the resulting array with GetArray.
For the record, I wanted VBScript code for a large userbase as a logon script that has the least chance of failing. I like the ADO objects, but there are so many mysterious ways ADO can be broken, so I shy away from ADODB.Stream.
Instead, I was able to write conversion code to convert binary to hex encoded strings. Then, to write back to a REG_BINARY value, I convert it to an array of integers and give it to the SetBinaryValue WMI method.
Note: WshShell can only handle REG_BINARY values containing 4 bytes, so it's unusable.
Thank you for the feedback.
Perhaps...
result = CStr(val1) & CStr(val2)
Related
I have hunted about quite a bit but can't find a way to get at the Hexadecimal or Binary representation of the content of a Double variable in VB6. (Are Double variables held in IEEE754 format?)
The provided Hex(x) function is no good because it integerizes its input first.
So if I want to see the exact bit pattern produced by Atn(1), Hex(Atn(1)) does NOT produce it.
I'm trying to build a mathematical function containing If clauses. I want to be able to see that the values returned on either side of these boundaries are, as closely as possible, in line.
Any suggestions?
Yes, VB6 uses standard IEEE format for Double. One way to get what you want without resorting to memcpy() tricks is to use two UDTs. The first would contain one Double, the second a static array of 8 Byte. LSet the one containing the Double into the one containing the Byte array. Then you can examine each Byte from the Double one by one.
If you need to see code let us know.
[edit]
At the module level:
Private byte_result() As Byte
Private Type double_t
dbl As Double
End Type
Private Type bytes_t
byts(1 To 8) As Byte
End Type
Then:
Function DoubleToBytes (aDouble As Double) As Byte()
Dim d As double_t
Dim b As bytes_t
d.dbl = aDouble
LSet b = d
DoubleToBytes = b.byts
End Function
To use it:
Dim Indx As Long
byte_result = DoubleToBytes(12345.6789#)
For Indx = 1 To 8
Debug.Print Hex$(byte_result(Indx)),
Next
This is air code but it should give you the idea.
I have a global array variable g () which starts with 3 object values.
I then call a sub that uses as input one of the items in g, and that needs to create additional items in g, plus update the item provided.
Something along the lines of
Declaration:
Public g() As branch
Initialization:
ReDim g (1 To 3)
Set g(1) = br1
Set g(2) = br2
Set g(3) = br3
Code call of sub
Call chg (g(2))
Sub
Public Sub chg (ByRef br As branch)
r = UBound(g)
ReDim g (1 To r + 2)
... (rest of the code)
End Sub
The code errors on the Redim statement, with error text "This array is fixed or temporarily locked".
Why can't I change the size of the array in this sub? What to do different?
From the MSDN documentation:
You tried to redimension a module-level dynamic array, in which one
element has been passed as an argument to a procedure. For example, in
the following code, ModArray is a dynamic, module-level array whose
forty-fifth element is being passed by reference to the Test procedure.
There is no need to pass an element of the module-level array in this
case, since it's visible within all procedures in the module. However,
if an element is passed, the array is locked to prevent a deallocation
of memory for the reference parameter within the procedure, causing
unpredictable behavior when the procedure returns.
Dim ModArray() As Integer ' Create a module-level dynamic array.
Sub AliasError()
ReDim ModArray(1 To 73) As Integer
Test ModArray(45) ' Pass an element of the module-level array to the Test procedure.
End Sub
Sub Test(SomeInt As Integer)
ReDim ModArray (1 To 40) As Integer ' Error occurs here.
End Sub
One idea would be to pass the index of the array instead of the object itself.
I know that it isn't possible to generate a control array at runtime.
However, is it possible to have several control arrays that I sub in at different points, referred to via a variable? IE
dim CArray() as controls
CArray = Labels
Foo(CArray)
CArray = OtherLabels
Foo(CArray)
My attempts to do this so far lead to a compile-time error, as it won't allow the control array actually on the form to be referred to without using a method or element. It gives the error:
Arugment not optional
You could use an object:
Private Sub Form_Load()
Dim CArray As Object
Set CArray = Labels
Foo CArray
End Sub
Sub Foo(CtrlArray As Object)
Dim i as Long
For i = 0 To CtrlArray.ubound
CtrlArray(i).Caption = Rnd
Next
End Sub
I'm having a really hard time finding an answer for this, with such generic terminology, and it's possible my question is still difficult to parse. I have some code with a variable representing the amount of free disk space remaining as a percentage. I want to call it into a function, where I use the reverse amount in a message to the user, i.e. the amount of used space. Can I do a little math in the function call?
Public Sub MyApp()
Dim nFreeSpace As Integer
nFreeSpace = GetFreeSpace
DisplayUsedSpace 100 - nFreeSpace 'Is this valid?
End Sub
Private Function DisplayUsedSpace(ByVal nUsedSpace As Integer) As Boolean
MsgBox("You have used " & nUsedSpace & "% of your disk drive space.")
End Function
Yes, that is valid. Although, I probably would write it as this
Call DisplayUsedSpace(100 - nFreeSpace)
But, your code would work fine too.
Of course you can - VB will calc the expression first.
You could also reverse it before the call
Public Sub MyApp()
Dim nUsedSpace As Integer
nUsedSpace = 100 - GetFreeSpace
DisplayUsedSpace nUsedSpace
End Sub
If you want it really compact:
Public Sub MyApp()
Call DisplayUsedSpace(100 - GetFreeSpace)
End Sub
I have the following structures defined (names are anonymised, but data types are correct):
Public Type ExampleDataItem
Limit As Integer ' could be any value 0-999
Status As Integer ' could be any value 0-2
ValidUntil As Date ' always a valid date
End Type
Public Type ExampleData
Name As String ' could be 5-20 chars long
ValidOn As Date ' could be valid date or 1899-12-30 representing "null"
Salt As Integer ' random value 42-32767
Items(0 To 13) As ExampleDataItem
End Type
I would like to generate a 32-bit hash code for an ExampleData instance. Minimising hash collisions is important, performance and data order is not important.
So far I have got (in pseudocode):
Serialise all members into one byte array.
Loop through the byte array, reading 4 bytes at a time into a Long value.
XOR all the Long values together.
I can't really post my code because it's heavily dependent on utility classes to do the serialisation, but if anyone wants to see it regardless then I will post it.
Will this be OK, or can anyone suggest a better way of doing it?
EDIT:
This code is being used to implement part of a software licensing system. The purpose of the hash is to confirm whether the data entered by the end user equals the data entered by the tech support person. The hash must therefore:
Be very short. That's why I thought 32 bits would be most suitable, because it can be rendered as a 10-digit decimal number on screen. This is easy, quick and unambiguous to read over the telephone and type in.
Be derived from all the fields in the data structure, with no extra artificial keys or any other trickery.
The hash is not required for lookup, uniqueness testing, or to store ExampleData instances in any kind of collection, but only for the one purpose described above.
Can you use the CRC32? Steve McMahon has an implementation. Combine that with a bit of base32 encoding and you've got something short enough to read over the phone.
Considering that performance is not an objective, if file size is not important and you want a unique value for each item. Just add an ID field. It data type is a string. Then use this function to generate a GUID. This will be a unique ID. Use it as a key for a dictonary or collection.
Public Type GUID
Data1 As Long
Data2 As Integer
Data3 As Integer
Data4(7) As Byte
End Type
Public Type GUID2 '15 BYTES TOTAL
Data1(14) As Byte
End Type
Public Declare Function CoCreateGuid Lib "OLE32.DLL" (pGuid As GUID) As Long
Public Function GetGUID() As String
Dim VBRIG_PROC_ID_STRING As String
VBRIG_PROC_ID_STRING = "GetGUID()"
Dim lResult As Long
Dim lguid As GUID
Dim MyguidString As String
Dim MyGuidString1 As String
Dim MyGuidString2 As String
Dim MyGuidString3 As String
Dim DataLen As Integer
Dim StringLen As Integer
Dim i As Integer
On Error GoTo error_olemsg
lResult = CoCreateGuid(lguid)
If lResult = 0 Then
MyGuidString1 = Hex$(lguid.Data1)
StringLen = Len(MyGuidString1)
DataLen = Len(lguid.Data1)
MyGuidString1 = LeadingZeros(2 * DataLen, StringLen) & MyGuidString1
'First 4 bytes (8 hex digits)
MyGuidString2 = Hex$(lguid.Data2)
StringLen = Len(MyGuidString2)
DataLen = Len(lguid.Data2)
MyGuidString2 = LeadingZeros(2 * DataLen, StringLen) & Trim$(MyGuidString2)
'Next 2 bytes (4 hex digits)
MyGuidString3 = Hex$(lguid.Data3)
StringLen = Len(MyGuidString3)
DataLen = Len(lguid.Data3)
MyGuidString3 = LeadingZeros(2 * DataLen, StringLen) & Trim$(MyGuidString3)
'Next 2 bytes (4 hex digits)
GetGUID = MyGuidString1 & MyGuidString2 & MyGuidString3
For i = 0 To 7
MyguidString = MyguidString & Format$(Hex$(lguid.Data4(i)), "00")
Next i
'MyGuidString contains last 8 bytes of Guid (16 hex digits)
GetGUID = GetGUID & MyguidString
Else
GetGUID = "00000000" ' return zeros if function unsuccessful
End If
Exit Function
error_olemsg:
GetGUID = "00000000"
Exit Function
End Function
Public Function LeadingZeros(ExpectedLen As Integer, ActualLen As Integer) As String
LeadingZeros = String$(ExpectedLen - ActualLen, "0")
End Function
EDIT: the question has now been edited to clarify that the goal is detecting typing errors, not minimizing collisions between totally different values. In that case Dan F's answer is the best one IMHO, not my offering below (wonderful though it is).
You could use the Microsoft CryptoAPI rather than rolling your own hash algorithm.
For instance this Microsoft article on using CryptoAPI from VB6 should get you started.
Or this from Edanmo on mvps.org for hashing a string in VB6.
EDIT: Following comment. If you insist on a 32-bit value, it will be hard to minimize hash collisions. My algorithm book suggests using Horner's method as a decent general purpose hashing algorithm. I don't have time right now to find out more information and implement in VB6. CopyMemory would probably be useful :)
You may be overthinking it, or I'm not understanding the issue. You could essentially just
hash(CStr(Salt) + Name + CStr(ValidOn) + Anyotherstrings
There is no particular need to go through the process of serializing into byte array and XORing values. Infact XORing values together in that way is more likely to create hash collisions where you aren't intending them.
Edit: I think I understand now. You're creating your own hash value by XORing the data together? It's unfortunately quite likely to give collisions. I know VB6 doesn't include any hashing algorithms, so you may be best importing and using something like Phil Fresle's SHA256 implementation.