1 //Written in the D programming language
2 /*
3  * Conversion routines.
4  *
5  * Copyright (C) 2013 Jaypha
6  *
7  * Distributed under the Boost Software License, Version 1.0.
8  * (See http://www.boost.org/LICENSE_1_0.txt)
9  *
10  * Authors: Jason den Dulk
11  */
12 
13 module jaypha.conv;
14 
15 //----------------------------------------------------------------------------
16 // Converts an unsigned interger into a hex string.
17 
18 alias binToHex bin2hex;
19 
20 @safe pure nothrow string binToHex(T)(T i) if(__traits(isUnsigned,T))
21 {
22   enum size = T.sizeof * 2;
23 
24   static immutable char[16] hex = "0123456789ABCDEF";
25   char[size] x;
26   foreach(j;0..size)
27   {
28     x[size-(j+1)] = hex[i%16];
29     i = i >>> 4;
30   }
31   return x.idup;
32 }
33 
34 
35 //----------------------------------------------------------------------------
36 // Extract the bits from a number and puts them into an array.
37 // eg. 01101b => [ 1000b, 100b, 1b ].
38 
39 @safe pure nothrow T[] bitsToList(T)(T bits) if(__traits(isIntegral,T) && __traits(isUnsigned,T))
40 {
41   T c = 1;
42   T[] r;
43 
44   while (bits != 0)
45   {
46     if (bits & 1)
47       r ~= c;
48     bits = bits >>> 1;
49     c = c << 1;
50   }
51   return r;
52 }
53 
54 //----------------------------------------------------------------------------
55 // Reduces an array to a single value by or-ing them together.
56 
57 @safe @nogc pure nothrow T listToBits(T)(T[] list) if(__traits(isIntegral,T) && __traits(isUnsigned,T))
58 {
59   // TODO explore using std.algorithm.reduce.
60   T bits;
61 
62   foreach (l;list)
63   {
64     bits |= l;
65   }
66   return bits;
67 }
68 
69 //----------------------------------------------------------------------------
70 
71 unittest
72 {
73   assert(binToHex(10u) == "0000000A");
74   assert(binToHex(10uL) == "000000000000000A");
75   assert(binToHex(0xB4C58A6Eu) == "B4C58A6E");
76   assert(binToHex(0x8765432u)  == "08765432");
77   assert(binToHex(0x4B8DA00Cu) == "4B8DA00C");
78   assert(bitsToList(0x7Au) == [ 2, 8, 16, 32, 64 ]);
79   assert(listToBits([ 64u, 32, 16,  8, 2 ]) == 0x7A);
80 }