Use Excel VBA to convert a decimal floating point to a binary number

Source: Internet
Author: User


1. Excel tools/macro/analysis tools/
There are indeed similar functions in which the decimal number can be easily converted to binary. However, the fatal disadvantage of this function is that it can only be replaced.

-512 ~ An integer between 511 and beyond this range.

Therefore, we can only use VBA to write an available function.


2.2.alt + F11 or
Tool/macro/Visual Basic Editor/
, Insert the module into the following functions


Function n10to2 (byval B as long) as string 'this function was got from Internet.

Dim A as long

Dim A1 as string

Dim s as string

Do

A = B mod 2

A1 = CSTR ()

S = A1 & S

B = B/2

Loop until B = 0

N10to2 = s

End Function

 

Function decto2 (byval B, byval C as long) as string 'wrote by myself

Dim A1 as string

Dim s as string

Dim t as double

T = cdec (B)

Do

T = T * 2 #

A1 = CSTR (t)

If T> 1 then

T = t-1

S = S & "1"

Else

S = S & "0"

End if

C = C-1

Loop until C <= 0

Decto2 = s

End Function


3. Split the floating point into integer and decimal parts. The preceding two functions are used to convert the integer part into a binary string, and the latter is used to convert the fractional part into a binary string.


4. Combine the symbols, indexes, and tails into a complete binary number.



 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.