Thread overview
Converting Hex string "0x001C" to long
Oct 20, 2007
jicman
Oct 21, 2007
jicman
Oct 21, 2007
Frank Benoit
October 20, 2007
Greetings.

I am working with a Windows COM program and I am getting a hex string like this, "0x001C", and I would like to change it to a long.  I tried a few things, but std.conv conversion is failing.

Any help would be greatly appreciated?

thanks,

josé
October 21, 2007
jicman Wrote:

> Greetings.
> 
> I am working with a Windows COM program and I am getting a hex string like this, "0x001C", and I would like to change it to a long.  I tried a few things, but std.conv conversion is failing.
> 
> Any help would be greatly appreciated?
> 
> thanks,
> 
> josé

found this,

http://www.digitalmars.com/d/archives/digitalmars/D/learn/read_Hexadecimal_value_from_string_8632.html#N8633

import std.string, std.stdio;
import std.c.stdlib;

long hexToLong(string s)
{
	long v = strtoul(toStringz(s), null, 16);
	if (getErrno() == ERANGE) throw new Exception("Out of range");
	return v;
}

void main()
{
	writefln("%d",hexToLong("0xC"));
}
October 21, 2007
jicman schrieb:
> jicman Wrote:
> 
>> Greetings.
>>
>> I am working with a Windows COM program and I am getting a hex string like this, "0x001C", and I would like to change it to a long.  I tried a few things, but std.conv conversion is failing.
>>
>> Any help would be greatly appreciated?
>>
>> thanks,
>>
>> josé
> 
> found this,
> 
> http://www.digitalmars.com/d/archives/digitalmars/D/learn/read_Hexadecimal_value_from_string_8632.html#N8633
> 
> import std.string, std.stdio;
> import std.c.stdlib;
> 
> long hexToLong(string s)
> {
> 	long v = strtoul(toStringz(s), null, 16);
> 	if (getErrno() == ERANGE) throw new Exception("Out of range");
> 	return v;
> }
> 
> void main()
> {
> 	writefln("%d",hexToLong("0xC"));
> }

Your example above uses toStringz which does a heap allocation. This is no good choice if you need to do this convertion a lot.

the tango.text.convert.Integer module has a parse function which takes a base argument. Just cut the "0x".

Anyway, doing your own implementation is not so hard :)