How do you get a hexstring from a base10 string -or- from a number?

Enjoys Math via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Wed Feb 3 15:57:46 PST 2016


On Wednesday, 3 February 2016 at 23:45:15 UTC, Enjoys Math wrote:
> On Wednesday, 3 February 2016 at 23:43:45 UTC, Enjoys Math 
> wrote:
>> I am making a method called:
>>
>> @property string debugIDString() {
>> in {
>>   assert(super.toHash() == this.toHash());
>> } body {
>>
>> }
>
> body { // is currently:
>   return to!string(this.toHash());
> }
>
> and is returning a base10 string, so how would I return a hex 
> string so I can compare numbers displayed to the debugger 
> addresses in visual D?

One solution:  create "string_tools.d":

module string_tools;
import std.conv: to;


string hexString(int x) {
	string hex = "0x";

	for(uint k=0; k < 8; k++) {
		int hexDig = (x >> (k << 2)) & 0x0000000F;
		if (hexDig < 10) {
			hex ~= to!string(hexDig);
		}
		else {
			string hexDixStr;
			switch (hexDig) {
				case 10:	hexDigStr = "A"; break;
				case 11:    hexDigStr = "B"; break;
				case 12:    hexDigStr = "C"; break;
				case 13:    hexDigStr = "D"; break;
				case 14:    hexDigStr = "E"; break;
				case 15:    hexDigStr = "F"; break;
			}
			hex ~= hexDigStr;
		}
	}

	return hex;
}


More information about the Digitalmars-d-learn mailing list