How can I copy the bits from a double to a long and back.

Jeff Ayers 1 Reputation point
2022-02-09T01:29:13.123+00:00

I am wanting to copy the bits from a double precision floating point variable into a long variable for analysis. In some instances, I will need to alter some bits and then copy the bits of the long back to the double.
What is the quickest and/or easiest way to do that using Visual Basic .net?

VB
VB
An object-oriented programming language developed by Microsoft that is implemented on the .NET Framework. Previously known as Visual Basic .NET.
2,617 questions
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 113.7K Reputation points
    2022-02-09T07:02:11.443+00:00

    Check an example:

    Dim d As Double = 1.2345E+67
    
    ' Double to Long '
    Dim b As Byte() = BitConverter.GetBytes(d)
    Dim l As Long = BitConverter.ToInt64(b)
    
    ' Long to Double '
    Dim b2 As Byte() = BitConverter.GetBytes(l)
    Dim d2 As Double = BitConverter.ToDouble(b2)
    

    Instead of modifying the long, you can modify the bytes of array.

    2 people found this answer helpful.
    0 comments No comments

  2. Jiachen Li-MSFT 27,496 Reputation points Microsoft Vendor
    2022-02-09T06:02:19.707+00:00

    Hi @Jeff Ayers ,
    I'm not sure what the result you want is.
    The code below may have what you want.

            Dim d1 As Double = 12345.6789  
            Dim d2 As Double  
            Dim l1 = Convert.ToInt64(d1)  
            Dim l2 As Long  
            Dim l3 As Long  
            Dim ind = d1.ToString.IndexOf(".")  
            l2 = d1.ToString.Split(".")(0)  
            l3 = d1.ToString.Replace(".", "")  
            d2 = l3.ToString.Insert(ind, ".")  
    

    d1=12345.6789
    l1=12346 Converting directly with convert.toint32 will lose the fractional part and precision
    l2=12345 After converting to a string, use split to get the part before the decimal point
    l3=123456789 Remove decimal point after converting to string
    d2=12345.6789 Add a decimal point in the original position
    Hope these are helpful.
    Otherwise please provide more information to help us understand what the result you want.
    Best Regards.
    Jiachen Li

    ----------

    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments