Vba excel hex to dec

I am trying to convert a Hexadecimal value to a decimal one in excel with this reference.

Used parameters and formulas:

Input Hex value : 0x044F3B9AFA6C80 and expected output : 1213017328610432

  • Method1: Applying excel formula

=HEX2DEC(RIGHT(D3164,10))+HEX2DEC(MID(D3164,3,4))*POWER(16,10)

Actual output : 1213017328610430

  • Method2: Using VBA macro:
    ' Force explicit declaration of variables
    Option Explicit

    ' Convert hex to decimal
    ' In:   Hex in string format
    ' Out:  Double

    Public Function HexadecimalToDecimal(HexValue As String) As Double

    ' If hex starts with 0x, replace it with &H to represent Hex that VBA will understand
    Dim ModifiedHexValue As String
    ModifiedHexValue = Replace(HexValue, "0x", "&H")

    HexadecimalToDecimal = CDec(ModifiedHexValue)
    End Function

Actual output : 1213017328610430

When I try to convert this value with online conversion tool or with python script, it covert expected decimal value.

Please any hint on issue will be more helpful.

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

WorksheetFunction.Hex2Dec method (Excel)

vbaxl10.chm137262

vbaxl10.chm137262

excel

Excel.WorksheetFunction.Hex2Dec

e2e0614c-583e-8a1f-b852-683c119d5a5a

05/23/2019

medium

WorksheetFunction.Hex2Dec method (Excel)

Converts a hexadecimal number to decimal.

Syntax

expression.Hex2Dec (Arg1)

expression A variable that represents a WorksheetFunction object.

Parameters

Name Required/Optional Data type Description
Arg1 Required Variant Number — the hexadecimal number that you want to convert. Number cannot contain more than 10 characters (40 bits). The most significant bit of number is the sign bit. The remaining 39 bits are magnitude bits. Negative numbers are represented using two’s-complement notation.

Return value

String

Remarks

If number is not a valid hexadecimal number, Hex2Dec returns the #NUM! error value.

[!includeSupport and feedback]

HEX2DEC
Show All
Hide All
Converts a hexadecimal number to decimal.

If this function is not available, and returns the #NAME? error, install and load the Analysis ToolPak add-in.

How?

On the Tools menu, click Add-Ins.
In the Add-Ins available list, select the Analysis ToolPak box, and then click OK.
If necessary, follow the instructions in the setup program.
Syntax

HEX2DEC(number)

Number is the hexadecimal number you want to convert. Number cannot contain more than 10 characters (40 bits). The most significant bit of number is the sign bit. The remaining 39 bits are magnitude bits. Negative numbers are represented using two’s-complement notation.

Remark

If number is not a valid hexadecimal number, HEX2DEC returns the #NUM! error value.

Example

The example may be easier to understand if you copy it to a blank worksheet.

How to copy an example

Create a blank workbook or worksheet.
Select the example in the Help topic.
Note Do not select the row or column headers.

Selecting an example from Help

Press CTRL+C.
In the worksheet, select cell A1, and press CTRL+V.
To switch between viewing the results and viewing the formulas that return the results, press CTRL+` (grave accent), or on the Tools menu, point to Formula Auditing, and then click Formula Auditing Mode.

1
2
3
4
A B
Formula Description (Result)
=HEX2DEC(«A5») Converts hexadecimal A5 to decimal (165)
=HEX2DEC(«FFFFFFFF5B») Converts hexadecimal FFFFFFFF5B to decimal (-165)
=HEX2DEC(«3DA408B9») Converts hexadecimal 3DA408B9 to decimal (1034160313)

HEX2DEC is limited to 10 characters, but that doesn’t mean we can’t use it. Simply use it several times, to convert 10 characters at a time and apply the appropriate power of 2 to each use.

= HEX2DEC(RIGHT(C8,10))+HEX2DEC(MID(C8,3,5))*POWER(16,10)

[Disclaimer: Untested at the moment]

Later: I’m now at a spreadsheet, ready to test. Change the 3,5 in MID to 3,6. Hmm.. Still not right.

Turns out that the HEX2DEC is working on signed hex values, so the first term ends up being negative. Not sure why, but here is the fixed version that adds 2^40 (or 16^10, as we’re working in hex) to fix:

= HEX2DEC(RIGHT(C8,10))+POWER(16,10) + HEX2DEC(MID(C8,3,6))*POWER(16,10)

However, that only works if the RIGHT(C8,10) happens to be negative. Here’s my general solution:

= HEX2DEC(RIGHT(C8,10))+IF(HEX2DEC(RIGHT(C8,10))<0,POWER(16,10),0) + HEX2DEC(MID(C8,3,6))*POWER(16,10)

Ugggh.

The following piece of VBA is an Microsoft Excel worksheet function that converts a 32 bit hex string into its decimal equivalent as an ieee 754 floating point (real) number — it returns a double.

This only works if the hexadecimal number is all in lower case and is exactly 8 characters (4 bytes) long. It could be extended easily to be a bit smarter, and even to do double precision numbers (64 bits) — but this works for me for what I wanted, and I couldn’t find it on the net anywhere else!

Function HEX2DECFL(strHexVal As String) As Double

‘ Function to convert 4 byte (32 bit) Hex value
‘ to a floating point decimal number
‘ using IEE 754

‘ Dave Stow

‘ Lookup array of hex digits to binary digits
Dim strBinaryDigits() As Variant

‘ String to put the full binary string into
Dim strBinaryString As String

‘ Each part of the floating point number
Dim intSign As Integer ‘ 1 or -1

Dim strExponentPart As String ‘ The bits making up the exponent
Dim intExponent As Integer ‘ The exponent itself

Dim strFraction As String ‘ The string that makes up the fractional part of the mantissa
Dim dblMantissa As Double ‘ The mantissa

Dim i As Integer

‘ Initialise the lookup tables for making the binary string
strBinaryDigits() = Array( _
«0000», «0001», «0010», «0011», _
«0100», «0101», «0110», «0111», _
«1000», «1001», «1010», «1011», _
«1100», «1101», «1110», «1111»)

‘ Generate binary string from hex
strBinaryString = «»
For i = 1 To Len(strHexVal)
strBinaryString = strBinaryString + strBinaryDigits(InStr(«0123456789abcdef», Mid(strHexVal, i, 1)) — 1)
Next

‘ Extract components of floating point number based on:
‘ bit 31 — sign bit
‘ bits 30-23 — exponent + 127 (127 is bias in 32 bit floats)
‘ bits 22-0 — fractional part of mantissa

‘ ————————————
‘ Sign — bit 31
If Left(strBinaryString, 1) = «1» Then
intSign = -1
Else
intSign = 1
End If

‘ ————————————
‘ Exponent — bits 30-23
strExponentPart = Mid(strBinaryString, 2, 8)
intExponent = 0
For i = 1 To 8
intExponent = intExponent + _
((2 ^ (8 — i)) * Val(Mid(strExponentPart, i, 1)))
Next

‘ Correct for bias of 127
intExponent = intExponent — 127

‘ ————————————
‘ Mantissa — bits 22-0
strFraction = Mid(strBinaryString, 10, 23)
dblMantissa = 0
For i = 1 To 23
‘ 2^i is 2, 4, 8, 16 etc
‘ 1/(2^i) is 1/2, 1/4, 1/8 etc
dblMantissa = dblMantissa + _
(Val(Mid(strFraction, i, 1)) * (1 / (2 ^ i)))
Next
‘ Add 1 as leading 1.xxxxxx is implicit
dblMantissa = dblMantissa + 1

‘ We’ve got all the bits — put it all together
HEX2DECFL = intSign * (dblMantissa * (2 ^ intExponent))

Источник

How can I convert four bytes of hexadecimal into a floating point number within Excel

I have copied a stream of hexadecimal data from a Wireshark capture into Excel as a text value with no spaces.

I know how to convert a section of this to an integer in Excel using the formula:

which in this case returns 299.

But how do I do something similar to retrieve a float? Some articles I’ve found discuss writing a C# program but I’m just trying to setup a little debug environment in Excel. Other articles only seem to discuss doing the conversion in the other direction but I couldn’t figure out the inverse procedure.

Edit: An example of what I am after is:

=SOMEFUNCTION(«d162c240») —> 6.062 (I think)

=SOMEFUNCTION(«c240» & «d162») —> 6.062

2 Answers 2

What a mission! But for anybody interested I got there, ending up with a custom LAMBDA function HexToFloat() that was built without the need for VBA. The LAMBDA function and several other functions used are new in Excel 365 — if you’re getting errors reproducing the functions below you might have an older version.

The Wikipedia page Single-precision floating-point format was my primary reference, in particular the section Converting binary32 to decimal.

Read the article for a full understanding (good luck!!), but for TLDR it’s worth noting that there is an implied bit that is not actually stored in memory and when combined with the fraction component this is referred to as the «significand».

For my solution I had to build several supporting LAMBDA functions in Excel’s Name Manager. In my case the data was stored as Little-Endian so if this is not applicable in your case you can skip that step.

Name Comment
LittleEndianHex Interpret Hex data as Little Endian by reversing it in 2-byte chunks
Name Comment
HEXtoBIN Handles bigger numbers than the native Excel HEX2BIN function
Name Comment
BINtoDEC Handles bigger numbers than the native Excel BIN2DEC function
Name Comment
HexToFloat Convert hexadecimal representation of little-endian IEEE 754 binary32 (4 bytes) number to Single-precision floating-point format

Once you’ve done all this you can enter the HexToFloat formula directly into a cell, e.g. =HexToFloat(A1) or =HexToFloat(«d162c240») . This particular example returns the result 6.07456254959106.

(PS I’ve never asked for votes before but this took me weeks! If you find it useful please consider giving me an up-tick.)

Источник

Hexadecimal to Decimal In Excel

I am trying to convert a Hexadecimal value to a decimal one in excel with this reference.

Used parameters and formulas:

Input Hex value : 0x044F3B9AFA6C80 and expected output : 1213017328610432

  • Method1: Applying excel formula

=HEX2DEC(RIGHT(D3164,10))+HEX2DEC(MID(D3164,3,4))*POWER(16,10)

Actual output : 1213017328610430

Actual output : 1213017328610430

When I try to convert this value with online conversion tool or with python script, it covert expected decimal value.

Please any hint on issue will be more helpful.

3 Answers 3

You can chop it into two parts:

I think the short answer is that you can’t get more than 15 digits of precision out of a Double data type, as noted in the comments. The only way to get the correct result is to use a Decimal data type, and you can only do this in VBA. In VBA, you can’t declare a Decimal type directly, but have to create it using Cdec and store it in a variant see documentation:

Thank you very much everyone. Finally I can able to covert hex to dec value with more then 16 digit. Excel only shows 16 digits in their each cells, so I have converted number into string helps me to present expected value in the cells.

Please find the final VBA code for any further reference.

‘ Force explicit declaration of variables Option Explicit

‘ Convert hex to decimal ‘ In: Hex in string format ‘ Out: Double Public Function HexadecimalToDecimal(HexValue As String) As String

Источник

Convert number From Excel cell to IEEE 754 Hex format

Recently I have been wrestling with Excel due to the 15 significant digits display limit for a number. I have been looking for a way to display the IEEE 754 format of a value contained in a Excel cell (since they are documented to work that way).

I’d prefer not to rely on VBA for this project (although I might get tempted if a memcpy -like solution is possible).

See my answer below for my current implementation. Any input or alternative is appreciated. I choose to believe that I missed an easier, well-tested solution.

1 Answer 1

The following sequence allow me to convert a number to its IEEE 754 hexadecimal representation using Excel formulas. I did not try to handle any exceptions besides 0. From Cell A1 to G1:

B1: =INT(LOG(ABS(A1);2)) Exponent

C1: =ABS(A1)/(2^B1) Mantissa

D1: =(C1-1)*(2^52) Convert mantissa to decimal

E1: =DEC2HEX(1023+B1+IF(A1 Convert sign & exponent to hex

F1: =CONCATENATE(DEC2HEX(D1/2^32;5);DEC2HEX(MOD(D1;2^32);8)) Convert decimal to hex.

A few of my result:

  • 22222.0948199999 > 0x40D5B3861187E7A5
  • =1.35632902954101*2^14 > 0x40D5B3861187E7A7
  • 22222.09482 > 0x40D5B3861187E7C0
  • 0.000123456 > 0x3F202E7EF70994DD
  • 1E+307 > 0x7FAC7B1F3CAC7433
  • -35.3 > 0xC041A66666666666
  • 1 > 0x3FF0000000000000

EDIT: Follow-up to chux comments.

We can see that the following value give a wrong result due to a rounding error:

Under this scenario, the value given at the step D1 is negative. If I use this information to update my exponent, my results appear to be consistent:

Источник

How can I convert a hex number to a decimal number in Excel?

I have a cell containing this value:

and I want to convert it to a number.

where C8 is the cell containing my hex value.

I get a #NUM error.

What am I doing wrong?

9 Answers 9

You could simply use:

len(A1) gives you the length of 0x string. Exclude the length of 0x , the remaining string is the hex number. Use Excel function to get the dec.

As TwiterZX indicated, Hex2Dec ‘s input is limited to 10 characters and 6cd2c0306953 is 12 characters. So that won’t work but let’s roll our own function for that. Using VBA, add a Module and use the following code (may need to be adjusted based on your needs)

In Excel, let’s say cell A1 contains 0x00006cd2c0306953 , A2’s formula of =HexadecimalToDecimal(A1) will result in 1.19652E+14 . Format the column to a number with zero decimals and the result will be 119652423330131 .

HEX2DEC is limited to 10 characters, but that doesn’t mean we can’t use it. Simply use it several times, to convert 10 characters at a time and apply the appropriate power of 2 to each use.

[Disclaimer: Untested at the moment]

Later: I’m now at a spreadsheet, ready to test. Change the 3,5 in MID to 3,6. Hmm.. Still not right.

Turns out that the HEX2DEC is working on signed hex values, so the first term ends up being negative. Not sure why, but here is the fixed version that adds 2^40 (or 16^10, as we’re working in hex) to fix:

However, that only works if the RIGHT(C8,10) happens to be negative. Here’s my general solution:

Источник

Adblock
detector

RRS feed

  • Remove From My Forums
  • Question

  • Any function can be used to perform such action?

All replies

  • Hello

    plz use HEX2DEC() function.

    but to use it, you should first install & load the ‘analysis tool pack’ addin.

    ‘=HEX2DEC(«FFFFFFFF5B»)’ produces -165. 

    sjoo

  • this function can be used in general excel operation after adding the add-in. However, If I write the macro, it seems that this function is not supported. Compilation error occur

  • hello again, ChrisKeung

    i see~

    here is another vba procedure. it would be helpful.

    Code Block

    Function Hex2Dec(n1 As String) As Long
        Dim nl1 As Long
        Dim nGVal As Long
        Dim nSteper As Long
        Dim nCount As Long
        Dim x As Long
        Dim nVal As Long
        Dim Stepit As Long
        Dim hVal As String

            nl1 = Len(n1)
        nGVal = 0
        nSteper = 16
        nCount = 1
        For x = nl1 To 1 Step -1
           hVal = UCase(Mid$(n1, x, 1))
           Select Case hVal
             Case «A»
               nVal = 10
             Case «B»
               nVal = 11
             Case «C»
               nVal = 12
             Case «D»
               nVal = 13
             Case «E»
               nVal = 14
             Case «F»
               nVal = 15
             Case Else
               nVal = Val(hVal)
           End Select
           Stepit = (nSteper ^ (nCount — 1))
           nGVal = nGVal + nVal * Stepit
           nCount = nCount + 1
        Next x
        Hex2Dec = nGVal
    End Function

In this article we will learn about some of the frequently asked Visual Basic programming questions in technical like “excel vba hex string to decimal” Code Answer. When creating scripts and web applications, error handling is an important part. If your code lacks error checking code, your program may look very unprofessional and you may be open to security risks. Error handling in VBA is simple. An error message with filename, line number and a message describing the error is sent to the browser. This tutorial contains some of the most common error checking methods in Visual Basic. Below are some solution about “excel vba hex string to decimal” Code Answer.

excel vba hex string to decimal

'VBA function to convert a hexadecimal string into a decimal. Uses
'the Decimal Variant subtype to allow for much larger values than the
'worksheet function HEX2DEC() or CLng("&h" & HexVal) can achieve. It 
'returns an UNSIGNED Decimal integer...
Function HexToDec(hexStr$)
    Static hexVals&(), b() As Byte
    If (Not Not hexVals) = 0 Then
    b = StrConv(hexStr, vbFromUnicode)
    For i = UBound(b) To 0 Step -1
        HexToDec = HexToDec + hexVals(b(i)) * bitVal
'-------------------------------------------------------------------------------------
MsgBox HexToDec("fffffffffffffffffffffff")  '<--displays: 4951760157141521099596496895
MsgBox TypeName(HexToDec("ABCDEF0123456"))  '<--displays: Decimal

Понравилась статья? Поделить с друзьями:
  • Vba excel goto пример
  • Vba excel goto next for
  • Vba excel google chrome
  • Vba excel get range address
  • Vba excel get hyperlink