Reading hexidecimal from a file
rikki cattermole via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sat Sep 10 05:23:05 PDT 2016
On 11/09/2016 12:18 AM, Basile B. wrote:
> On Saturday, 10 September 2016 at 12:12:28 UTC, Basile B. wrote:
>> On Saturday, 10 September 2016 at 12:04:08 UTC, Neurone wrote:
>>> Hi,
>>>
>>> I want to read a text file that contains sha1 hashes in hexidecimal,
>>> then convert the hashes back into ubyte[20]. Examples of some lines:
>>> E9785DC5 D43B5F67 F1B7D1CB 33279B7C 284E2593
>>> 04150E8F 1840BCA2 972BE1C5 2DE81039 0C486F9C
>>>
>>> How can I do this? The documentation for format strings is pretty
>>> dense, so couldn't understand most of it.
>>
>> at compile time you can do:
>>
>> import std.conv;
>> enum array = hexString!(import(theFile));
>>
>> the run-time version was proposed
>> (https://github.com/dlang/phobos/pull/4487) but not interesting enough ;)
>
> No actually, it has nothing to do with you question!
>
> what you have to do is probably:
>
> split join chunck(2) to!ubyte
>
> sorry leaving now.
Actually you'd want to filter out e.g. white space as well.
So the long form via an input range would be:
struct GetHex(T) {
string from;
T next;
this(string input) {
from = input;
popFront;
}
@property {
bool empty() { return from.length == 0 || next == 0; }
T front() { return next; }
}
void popFront() {
next = 0;
char[T.sizeof * 2] got;
ubyte count;
while(count < got.length && from.length > 0) {
got[count] = nextChar;
if (got[count] != 0)
count++;
}
import std.conv : parse;
if (count > 0) {
char[] temp = got[0 .. count];
next = parse!T(temp, 16);
}
}
char nextChar() {
char readIn = from[0];
from = from[1 .. $];
if ((readIn >= 'A' && readIn <= 'F') || (readIn >= 'a' && readIn <= 'f'))
return readIn;
else if (readIn >= '0' && readIn <= '9')
return readIn;
else
return 0;
}
}
void main() {
string source = "
E9785DC5 D43B5F67 F1B7D1CB 33279B7C 284E2593
04150E8F 1840BCA2 972BE1C5 2DE81039 0C486F9C";
import std.stdio : writeln;
writeln(GetHex!uint(source));
}
More information about the Digitalmars-d-learn
mailing list