digitalmars.D.learn - string to hex convert
- aerto (1/1) Mar 29 2018 how i can convert Hello world! to hex 48656c6c6f20776f726c6421 ??
- Cym13 (12/14) Mar 29 2018 Maybe something like:
- =?UTF-8?Q?Ali_=c3=87ehreli?= (31/48) Mar 29 2018 For fun, here's a lazy version that uses a table. Apparently,
- Seb (9/11) Mar 29 2018 ---
how i can convert Hello world! to hex 48656c6c6f20776f726c6421 ??
Mar 29 2018
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 2018
On 03/29/2018 02:23 PM, Cym13 wrote:On Thursday, 29 March 2018 at 20:29:39 UTC, aerto wrote: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() { } Alihow 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 2018
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 2018