Thanks:  0
Likes:  0
Dislikes:  0

Thread: Converting a Hex String value to an Integer

1. Converting a Hex String value to an Integer

I'm attempting to convert "0x000DC" to an integer
but within Silk when I attempt this with

string szVal = "0x000DC"
integer iVal = [INTEGER]szVal
Print('{iVal}')

It prints 48 ... I guess that's the ascii value of the first character.

Are there any functions out there that will return the correct value of 200???

2. Re: Converting a Hex String value to an Integer

Actually, base-16 "DC" is 220 in base-10 !

It's a silly question I know, but since I don't have the function with me here at home and will post it tomorrow, would you like to know how to convert any number base to base-10?

Consider the base-10 string "234" which obviously represents a sum of 200 + 30 + 4.

If you look at it with exponents the equivalent of these three values are:

(2*10^2) + (3*10^1) + (4*10^0)

Note the power progression from 0 to 2 starting from right to left. This same sequence - 0 to n -applies to any number base.

Now look a hex string such as "abc":

(a*16^2) + (b*16^1) + (c*16^0)

Of course "a", "b" and "c" here will need to be converted to their decimal equivalents 10, 11, and 12.

(10*16^2) + (11*16^1) + (12*16^0)

Cool huh? You can now convert any number base to its base-10 equivalent. So, a minor challenge: if I have "1a" eggs in base-12 (a dozen) how many eggs would that be in base-10? (No, you aren't allowed to use your toes.)

Not that you care (yet) but whereas this conversion is a matter of successive multiplication, going the other way from base-10 to base-n is a matter of successive division by the number base and using the remainers to identify individual base character values. Quick, what's 123456 base-10 in base-36 using characters 0-z??? What? You don't care? Me neither, it's late. Some other time perhaps...

[img]images/icons/smile.gif[/img]

John

3. Re: Converting a Hex String value to an Integer

Can't you just use the Val function?

iNum = Val("0x00DC")

While it doesn't state in the help file that this will work, neither does it state that it won't...

Dana

4. Re: Converting a Hex String value to an Integer

For one of us who just has WAY too much time on his or her hands, it might be neat to write a conversion function where you pass in the value you want to convert and the base you want to use.

e.g. DoConvert("0x000DC", "base12")

The more I think about this, the more permutations it has and it is beginning to be painful. Tell the voices in my head to stop!

5. Re: Converting a Hex String value to an Integer

There's one (hex-&gt;dec) in the Knowledge Base:

http://support.segue.com/kbshow.php?q=10425

There are several other ways to do it, but the above demonstrates a simple step-by-step method similar to how John described.

Paul.

Update - Just checked and the resolution one was wrong... I have replace it with a simplified and working version [img]images/icons/smile.gif[/img]

[ 03-12-2004, 05:07 AM: Message edited by: Paul Gregg ]

6. Re: Converting a Hex String value to an Integer

I have a set of functions which convert between decimal and base 34 with the digits in reverse order (bizarrely I've needed that but never hex or anything else more common). I'm in a bit of a rush at work at the moment so I don't have time to convert it myself, but I'm willing to post it 'as is', because starting from that it should be fairly easy to adapt and generalise it.

7. Re: Converting a Hex String value to an Integer

</font><blockquote><font size="1" face="Verdana, Arial, Helvetica">code:</font><hr /><pre style="font-size:x-small; font-family: monospace;">// HEX_TO_DECIMAL() - base-16 to base-10 converter
int hex_to_decimal(string sNum)
{
string s ;
int x, iVal ;
real sum = 0, y = 0 ;

sNum = Lower(sNum) ;

for x = Len(sNum) to 1 step -1
{
s = SubStr(sNum, x,1) ;
switch (s)
{
case &quot;0&quot;,&quot;1&quot;,&quot;2&quot;,&quot;3& quot;,&quot;4&quot;,&quot;5&quot;,&quot;6&quot;,&q uot;7&quot;,&quot;8&quot;,&quot;9&quot;:
{
iVal = Val(s) ;
break ;
}
case &quot;a&quot;,&quot;b&quot;,&quot;c&quot;,&quot;d& quot;,&quot;e&quot;,&quot;f&quot;:
{
iVal = Asc(s)-87 ; // &quot;-87&quot; adjusts offset so that &quot;a&quot;=10, &quot;b&quot;=11, &quot;c&quot;=12 ... , &quot;f&quot;=15
break ;
}
default:
{
raise 1, &quot;ERROR - character '{s}' is invalid in base-16' number system. Expected '0-9, a-f'.&quot; ;
}
}
sum += iVal *(16**y) ;
y += 1 ; // increment the exponent
}
return sum ;
}</pre><hr /></blockquote><font size="2" face="Verdana, Arial, Helvetica">DJGray,

I wrote the any base converter too, but it exposes some large-number issues that I want to investigate.

John

8. Re: Converting a Hex String value to an Integer

The following code is also available as Resolution 17077 at the Segue Software Knowledge Base

I hope you find it useful.

</font><blockquote><font size="1" face="Verdana, Arial, Helvetica">code:</font><hr /><pre style="font-size:x-small; font-family: monospace;">[ ] // ****************************************
[ ] // * number_base_conversion.t *
[ ] // ************************************************** ***************
[ ] // * *
[ ] // * *
[ ] // * NOTICE: This file and the functions are provided *
[ ] // * AS IS and are not supported by Segue Software in any *
[ ] // * way, shape, or form. *
[ ] // * *
[ ] // * Author: Paul Gregg &lt;pgregg@segue.com&gt; *
[ ] // * Date: 15th March 2004 *
[ ] // * Copyright (c) 2004 by Segue Software, Inc. *
[ ] // * *
[ ] // * *
[ ] // * This file contains generic functions for converting *
[ ] // * numbers to and from decimal using any base from 2 to 62 *
[ ] // * *
[ ] // * Also included is a Generic any-base-&gt;any-base number *
[ ] // * converter and a simple Hex2Decimal function. *
[ ] // * *
[ ] // * *
[ ] // * Synopsis: ******************
[ ] // * number ConvertHex2Dec (string sHex) *
[ ] // * number ConvertToDecFromBase (string sNumber, int iBase optional) *
[ ] // * string ConvertFromDecToBase (int iNumber, int iBase optional) *
[ ] // * string ConvertFromBaseToBase(string sNumber, int iBasefrom, int iBaseto) *
[ ] // * *
[ ] // * ******************
[ ] // ************************************************** ***************
[ ]
[ ]
[ ]
[ ]
[ ] // Small example of neatly converting hexadecimal to decimal
[-] number ConvertHex2Dec (string sHex)
[ ] int iDec = 0
[ ]
[ ] // Convert the hex string to lower case
[ ] sHex = lower(sHex)
[ ]
[ ] // remove an 0x from the start if it exists
[-] if substr(sHex, 1, 2) == &quot;0x&quot;
[ ] sHex = substr(sHex, 3)
[ ]
[ ] // Now loop through each charater from the end backwards adding it the sum
[ ]
[ ] int iLen = len(sHex)
[ ] int iAsc, i
[ ]
[-] for (i=iLen; i&gt;0; i--)
[ ] iAsc = Asc(sHex[i])
[-] if (iAsc &gt; 96) &amp;&amp; (iAsc &lt; 103)
[ ] iAsc = iAsc - 87 // &quot;a&quot; =&gt; 97 - 87 = 10; &quot;f&quot; =&gt; 102 - 87 = 15
[-] else
[ ] iAsc = Val(sHex[i]) // This must be a regular 0-9 digit
[ ] iDec = iDec + ( iAsc * (16**(iLen-i))) // Now convert the hexvalue+position to decimal
[ ]
[ ] return iDec
[ ]
[ ]
[ ]
[ ] // Convert a (string) number &quot;sNumber&quot; already in &quot;iBase&quot; base to decimal format.
[ ] // Returns a number value
[-] number ConvertToDecFromBase (string sNumber, int iBase optional)
[ ] int iDec = 0
[ ] int iAsc, i
[ ]
[-] if IsNull(iBase)
[ ] iBase = 0
[ ]
[-] switch(iBase)
[-] case 16
[ ] // remove an 0x from the start if it exists
[-] if (substr(sNumber, 1, 2) == &quot;0x&quot &#0124;&#0124; (substr(sNumber, 1, 2) == &quot;0X&quot
[ ] sNumber = substr(sNumber, 3)
[-] case 8
[ ] // remove the 0 from the start if it exists - not really required
[-] if (len(sNumber) &gt; 0) &amp;&amp; (sNumber[1] == '0')
[ ] sNumber = substr(sNumber, 2)
[-] case 2
[ ] // remove an 0b from the start if it exists
[-] if (substr(sNumber, 1, 2) == &quot;0b&quot &#0124;&#0124; (substr(sNumber, 1, 2) == &quot;0B&quot
[ ] sNumber = substr(sNumber, 3)
[-] default
[ ] // Look for numbers in the format base#number, if so split it up and use the base from it
[ ] i = strpos('#', sNumber)
[-] if i &gt; 0
[ ] iBase = Val(substr(sNumber, 1, i-1))
[ ] sNumber = substr(sNumber, i+1)
[-] else if iBase == 0
[ ] print(&quot;ConvertToDecFromBase called without a base value and not in base#number format: ({sNumber}, {iBase})&quot
[ ] return 0
[ ]
[ ] // Convert the number string to upper case since base36 or less is case insensitive
[-] if (iBase &lt;= 36)
[ ] sNumber = upper(sNumber)
[ ]
[ ] // By now we know we have a correct base and number
[ ] int iLen = len(sNumber)
[ ]
[ ] // Now loop through each charater from the end backwards adding it the sum
[ ]
[-] for (i=iLen; i&gt;0; i--)
[ ] iAsc = Asc(sNumber[i])
[-] if (iAsc &gt; 64) &amp;&amp; (iAsc &lt; 91) // A..Z
[ ] iAsc = iAsc - 55 // &quot;A&quot; =&gt; 65 - 55 = 10; &quot;F&quot; =&gt; 70 - 55 = 15; &quot;Z&quot; =&gt; 90 - 55 = 35
[-] else if (iAsc &gt; 96) &amp;&amp; (iAsc &lt; 123) // a..z (for base &gt; 32)
[ ] iAsc = iAsc - 61 // &quot;a&quot; =&gt; 97 - 61 = 36; &quot;f&quot; =&gt; 102 - 61 = 41; &quot;z&quot; = 122 - 61 = 61
[-] else
[ ] iAsc = Val(sNumber[i]) // This must be a regular 0-9 digit
[-] if (iAsc &gt;= iBase)
[ ] print(&quot;Error: {sNumber} is not a valid {iBase} number&quot
[ ] return 0
[ ] iDec = iDec + ( iAsc * (iBase**(iLen-i))) // Now convert the hexvalue+position to decimal
[ ]
[ ] return iDec
[ ]
[ ]
[ ]
[ ] // Convert a decimal number &quot;iNumber&quot; to any other base.
[ ] // Returns a string representation of the number in the new base.
[-] string ConvertFromDecToBase (int iNumber, int iBase optional)
[ ] string sNumber = '' // result
[ ] list of int liNumber // array holding the new number as it is being built
[ ] int iRem, iSize, i
[ ] string sChar
[ ]
[-] if (iNumber &gt; 0)
[-] while iNumber &gt; 0
[ ] iRem = iNumber % iBase
[ ] iNumber = iNumber / iBase
[ ] listappend(liNumber, iRem)
[ ] // Now loop through liNumber converting to characters and appending to sNumber
[ ] iSize = ListCount(liNumber)
[-] for(i=iSize; i&gt;0; i--)
[-] if liNumber[i] &lt; 10
[ ] sChar = Str(liNumber[i])
[-] else if liNumber[i] &lt; 36
[ ] sChar = Chr(liNumber[i] + 55)
[-] else
[ ] sChar = Chr(liNumber[i] + 61)
[ ] sNumber = sNumber + sChar
[-] else
[ ] sNumber = &quot;0&quot; // Special case for zero
[ ] return sNumber
[ ]
[ ]
[ ]
[ ] // Generic base conversion
[ ] // A &quot;Base to Base&quot; function which wraps the above functions making it easier to do base conversions
[ ] // not involving decimals
[ ] // Returns a string represenation of the entered number in the new base.
[-] string ConvertFromBaseToBase(string sNumber, int iBasefrom, int iBaseto)
[ ] return ConvertFromDecToBase(ConvertToDecFromBase(sNumber, iBasefrom), iBaseto)
[ ]
[ ]
[ ]
[ ]
[ ]
[ ] // Lots of examples - give this test case at least a minute to complete.
[-] testcase Examples() appstate none
[ ] int i, j
[ ] string sTest
[-] ResOpenList(&quot;ConvertHex2Dec examples.&quot
[-] for (j=0; j&lt;256; j++)
[ ] sTest = PrintfToString(&quot;%s%s&quot;, RandInt(0,1)==1 ? &quot;0x&quot; : &quot;&quot;, ConvertFromDecToBase(j, 16))
[ ] Print(&quot;Hex '{sTest}' =&gt; Dec&quot;, ConvertHex2Dec(sTest))
[ ]
[ ] // Print(ConvertHex2Dec(&quot;0xff&quot)
[ ] // Print(ConvertHex2Dec(&quot;100&quot)
[ ] // Print(ConvertHex2Dec(&quot;ffff&quot)
[ ] // Print(ConvertHex2Dec(&quot;0x000DC&quot)
[ ] ResCloseList()
[ ]
[ ]
[ ] print(&quot;&quot
[-] ResOpenList(&quot;ConvertToDecFromBase examples&quot
[-] for (i=2; i&lt;=62; i++)
[-] ResOpenList(&quot;Base {i} examples&quot
[-] for (j=0; j&lt;=256; j++)
[ ] sTest = ConvertFromDecToBase(j, i)
[ ] Print(&quot;{sTest} =&gt; Dec&quot;, ConvertToDecFromBase(sTest, i))
[ ] ResCloseList()
[ ] ResCloseList()
[ ]
[ ]
[ ] print(&quot;&quot
[-] ResOpenList(&quot;ConvertFromDecToBase examples&quot
[-] for (i=2; i&lt;=62; i++)
[-] ResOpenList(&quot;Base {i} examples&quot
[-] for (j=0; j&lt;=256; j++)
[ ] Print(&quot;Dec {j} to base {i} =&gt;&quot;, ConvertFromDecToBase(j, i))
[ ] ResCloseList()
[ ] ResCloseList()
[ ]
[ ]
[ ] print(&quot;&quot
[-] ResOpenList(&quot;ConvertFromBaseToBase (random) examples&quot
[ ] int k, l
[ ] string sNumber
[-] for (k=0; k&lt;=256; k++)
[ ] i = RandInt(2,62)
[ ] j = RandInt(2,62)
[ ] l = RandInt(100,1000) // test number
[ ] sNumber = ConvertFromDecToBase(l, i) // test number in 'original' base
[ ] Print(&quot;Base {i} {sNumber} (Decimal {l}) =&gt; to Base {j}&quot;, ConvertFromBaseToBase(sNumber, i, j))
[ ] ResCloseList()
[ ]
[ ]
[ ]
[ ] print(&quot;&quot
[ ] print(&quot;Test complete.&quot
[ ]
[ ]
[ ] </pre><hr /></blockquote><font size="2" face="Verdana, Arial, Helvetica">

Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•
Search Engine Optimisation provided by DragonByte SEO v2.0.36 (Pro) - vBulletin Mods & Addons Copyright © 2016 DragonByte Technologies Ltd.