Re: Re: converting hex strings
- To: mathgroup at smc.vnet.net
- Subject: [mg27464] Re: [mg27434] Re: converting hex strings
- From: maarten.vanderburgt at icos.be
- Date: Tue, 27 Feb 2001 00:37:17 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
Bob, Allan, Paul,
With the suggestion to use the " " around 16^^, it was not too difficult to
convert 32 bit floating point numbers in hexadecimal format to a decimal
number, knowing the IEEE format:
hexToFloat[x_String] := Module[{str, dig , expo, mant, tt},
str = StringJoin["16^^", x];
dig = IntegerDigits[ToExpression[str], 2];
dig = PadLeft[dig, 32];
expo = FromDigits[dig[[Range[2, 9]]], 2] - 127;
tt = Table[1./2^i, {i, 1, 23}];
mant = 1. + Plus @@ (tt*dig[[Range[10, 32]]]);
If[dig[[1]] == 0, mant 2^expo, -mant 2^expo]
];
In[72]:= hexToFloat[#]&/@{"42c80000", "bdfcd35b","3dfcd35b", "bf800000"}
Out[72]= {100., -0.12345, 0.12345, -1.}
Thanks a lot for your help
Maarten
"Paul Lutus" <nospam at nosite.com> on 26-02-2001 02:55:37 AM
cc:
Subject: [mg27464] [mg27434] Re: converting hex strings
<maarten.vanderburgt at icos.be> wrote in message
news:97a7b2$aks at smc.vnet.net...
> Hallo,
>
> I have a list of hexadecimal strings (read from a hex string text file):
> e.g. {"01a0", "fffe", "0080"} representing integers.
> How can I convert such a list to integers so that I get {416, 4094, 128}?
> I cannot make a function using something like
>
> hextoint = 16^^#&
>
> or
>
> hextoin = 16^^ToExpression[#]&
>
> I get errors like below:
>
> In[44]:= hexstr = "a1b0"
> t = ToExpression[hexstr];
> 16^^t
> General::"digit": "Digit at position \!\(1\) in \!\(\"t\"\) is too large
to
> \
> be used in base \!\(16\)."
>
> Where does this error come from?
>
> While this works ok:
> In[43]:= 16^^a1b0
> Out[43]= 41392
>
> The ToExpression[ ] also would give problems: ToExpression["01a0"]
returns
> 0.
>
> Has anyone done anything along these lines?
I think this will do it for you:
myhex[x_String] := Module[
{str},
str = StringJoin["16^^",x];
ToExpression[str]
];
data = {"01a0","fffe","0080"};
Map[myhex,data]
{416,65534,128}
> How would I have to convert a hex list representing floats (IEEE floating
> point standard)?, e.g. {"42c8000", "3dfcd35b", "bf80000"} which should
> convert to {100.0, 0.12345, -1.0} in a decimal notation.
I think that will be much more difficult -- it will require a full grasp of
the IEEE specification within the converter code.
--
Paul Lutus
www.arachnoid.com