Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Quick convert of byte array-to-string and string-to-byte array

Status
Not open for further replies.

Guest_imported

New member
Jan 1, 1970
0
ey dudes, anybody out there knows of a quick way to convert byte array-to-string and string-to-byte array...mine was to slow, needs a more fast one...can u send me a code thanks...my_vbcode@einan-online.8m.com
 
Hi,

You can:
----------------------------
Dim a() As Byte, s As String
a = "hello"
s = a
----------------------------

But why? Try
----------------------------
Dim a() As Byte
a = "hello"
MsgBox a
----------------------------

And if that is not enough, check out the ultra fast string to byte array method (the reverse is also be possible). Notice that none of the data is actually moved in memory - its all manipulation of the safearray structure (and you could also convert to singles, doubles or whatever).
------------------------------------------------------------
Option Explicit
Private Type SAFEARRAYBOUND
cElements As Long
lLbound As Long
End Type

Private Type SAFEARRAY1D
cDims As Integer
fFeatures As Integer
cbElements As Long
cLocks As Long
pvData As Long
Bounds(0 To 0) As SAFEARRAYBOUND
End Type

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (lpvDest As Any, lpvSource As Any, ByVal cbCopy As Long)
Private Declare Function VarPtrArray Lib "msvbvm60.dll" Alias "VarPtr" (Var() As Any) As Long

Private Sub Command1_Click()
Dim Ssa As SAFEARRAY1D, SsaPtr As Long
Dim SArr() As Byte, S As String
S = "Hello" 'Create new string
ReDim SArr(0) 'create the safearray structure
CopyMemory SsaPtr, ByVal VarPtrArray(SArr), 4 'Get a pointer to the SafeArray structure
CopyMemory Ssa, ByVal SsaPtr, Len(Ssa) 'Copy the safearray stucture into varaible Ssa
Ssa.pvData = StrPtr(S) 'Cheating! set the data pointer to point to the string memory
Ssa.Bounds(0).cElements = LenB(S) 'Define the length of the array
CopyMemory ByVal VarPtrArray(SArr), VarPtr(Ssa), 4 'Copy the new info back to the SafeArray

MsgBox SArr 'test

CopyMemory ByVal VarPtrArray(SArr), 0&, 4 'Clean up
End Sub
------------------------------------------------------------ Sunaj
'The gap between theory and practice is not as wide in theory as it is in practice'
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top