FormattedRead hex string

Jason Spencer spencer8 at sbcglobal.net
Mon Sep 24 08:06:40 PDT 2012


I imagine there's a slick way to do this, but I'm not seeing it.

I have a string of hex digits which I'd like to convert to an 
array of 8 ubytes:

0123456789abcdef --> [0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 
0xEF]

I'm looking at std.format.formattedRead, but the documentation 
is...lightish.  First of all, it seems there's no format 
specifier except %s on reads and type information is gleaned from 
the args' types.  I was able to experiment and show that %x 
works, but no documentation on exactly how.

Second, array syntax seems to work only if there's some 
delimiter.  With:

void main(string[] args)
{
    ubyte[8] b;

    formattedRead(args[1], "%(%s%)", &b);
}

I get

std.conv.ConvOverflowException at C:\Tools\D\dmd2\windows\bin\..\..\src\phobos\std\
conv.d(2006): Overflow in integral conversion

at least once. :)  But that makes sense--hard to tell how many 
input chars to assign to one byte versus another (although it 
seems to me a hungry algorithm would work--saturate one type's 
max and move to the next.)

There doesn't seem to be any support for field sizes or counts in 
formatted read, similar to old C "%16x".  This barks at me right 
away--"%1 not supported."

I know I could read (in this case) as two longs or a uint16, but 
I don't want to deal with endianess--just data.

Is there some trick to use the fact that b is fixed size 8 bytes 
and know that requires 16 hex digits and converts automatically?  
Is there some other suggestion for how to do this eloquently?  I 
can play around with split and join, but it seemed like there is 
probably some way to do this directly that I'm  not seeing.

Thanks!
Jason


More information about the Digitalmars-d-learn mailing list