read Hexadecimal value from string

Regan Heath regan at netmail.co.nz
Tue Jul 17 07:24:50 PDT 2007


Gilles G. wrote:
> Hello,
> I try to read hexadecimal values from a file.
> I tryed to use toInt, for example:
> auto i = toInt("C");
> but this doesn't work.
> What is the method to read hexadecimal value?
> 
> Thanks.

Oddly, std.conv doesn't have a routine for it, as far as I am aware. 
Here's how I would do it.

/* http://www.opensource.org/licenses/cpl1.0.php */

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"));
}


More information about the Digitalmars-d-learn mailing list