www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - string to hex convert

reply aerto <cvsc gmx.com> writes:
how i can convert Hello world! to hex 48656c6c6f20776f726c6421 ??
Mar 29
next sibling parent reply Cym13 <cpicard openmailbox.org> writes:
On Thursday, 29 March 2018 at 20:29:39 UTC, aerto wrote:
 how i can convert Hello world! to hex 48656c6c6f20776f726c6421 
 ??
Maybe something like: void main() { // Those look like lots of imports but most of those are very common anyway import std.digest: toHexString; import std.stdio: writeln; string s = "Hello world!"; (cast(ubyte[]) s) // We want raw bytes... .toHexString // ...convert them to hex... .writeln; // ...and print. }
Mar 29
parent =?UTF-8?Q?Ali_=c3=87ehreli?= <acehreli yahoo.com> writes:
On 03/29/2018 02:23 PM, Cym13 wrote:
 On Thursday, 29 March 2018 at 20:29:39 UTC, aerto wrote:
 how i can convert Hello world! to hex 48656c6c6f20776f726c6421 ??
Maybe something like: void main() {     // Those look like lots of imports but most of those are very common anyway     import std.digest: toHexString;     import std.stdio: writeln;     string s = "Hello world!";     (cast(ubyte[]) s)    // We want raw bytes...         .toHexString     // ...convert them to hex...         .writeln;        // ...and print. }
For fun, here's a lazy version that uses a table. Apparently, toHexString does not use a table. I'm not measuring which one is faster. :) (Note: toHexString allocates memory, so it wouldn't be a fair comparison anyway.) string asHex(char i) { import std.string : format; import std.algorithm : map; import std.range : iota, array; enum length = char.max + 1; static const char[2][length] hexRepresentation = iota(length).map!(i => format("%02x", i)).array; return hexRepresentation[i]; } unittest { assert(0.asHex == "00"); assert(128.asHex == "80"); assert(255.asHex == "ff"); } auto asHex(string s) { import std.string : representation; import std.algorithm : map, joiner; return s.representation.map!asHex.joiner; } unittest { import std.algorithm : equal; assert("Hello wörld!".asHex.equal("48656c6c6f2077c3b6726c6421")); } void main() { } Ali
Mar 29
prev sibling parent Seb <seb wilzba.ch> writes:
On Thursday, 29 March 2018 at 20:29:39 UTC, aerto wrote:
 how i can convert Hello world! to hex 48656c6c6f20776f726c6421 
 ??
--- import std.format, std.stdio; void main() { writeln("Hello World!".format!("%(%02X%)")); } --- https://run.dlang.io/is/acz7kV
Mar 29