Converting single precision float to a 4 byte string

Posted on 2003-03-01
Medium Priority
Last Modified: 2012-06-27
I need a function to convert a single precision floating point into a 4 byte string (so that I can story it into a binary file).

I have tried to do this by creating the function below

Public Declare Sub RtlMoveMemory Lib "kernel32" (ByVal hpvDest As Long, ByVal hpvSource As Long, ByVal cbCopy As Long)

Function floattostring(byval tFloat as single) as String
  dim sBuffer As String

  sBuffer = String(4, vbNullChar)
  RtlMoveMemory StrPtr(sBuffer), VarPtr(tFloat), 4
  floattostring = sBuffer
end function

however it doesn't seem to work (the string returned is always the 4 bytes "3F 3F 00 00").

Does anyone know a simple way I could convert this (either using memory copy/read api or actually converting it using an vb function)
Question by:dummstah
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions

Accepted Solution

DocM earned 200 total points
ID: 8047597

 Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" ( _
  hpvDest As Any, hpvSource As Any, _
  ByVal cbCopy As Long)

Private Sub Single_To_4BytesString()

Dim str1 As String
Dim sng As Single

sng = 1.23456789

str1 = String(4, vbNullChar)
Call CopyMemory(ByVal str1, sng, 4)
For i = 1 To 4
 Debug.Print Asc(Mid(str1, i, 1)); " ";

End Sub

Author Comment

ID: 8047631
Works perfectly. Thanks a lot.

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
This article describes how to use a set of graphical playing cards to create a Draw Poker game in Excel or VB6.
Get people started with the process of using Access VBA to control Excel using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Excel. Using automation, an Access application can laun…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses

801 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question