Thread overview | ||||||
---|---|---|---|---|---|---|
|
March 29, 2018 string to hex convert | ||||
---|---|---|---|---|
| ||||
how i can convert Hello world! to hex 48656c6c6f20776f726c6421 ?? |
March 29, 2018 Re: string to hex convert | ||||
---|---|---|---|---|
| ||||
Posted in reply to aerto | 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.
}
|
March 29, 2018 Re: string to hex convert | ||||
---|---|---|---|---|
| ||||
Posted in reply to aerto | 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 |
March 29, 2018 Re: string to hex convert | ||||
---|---|---|---|---|
| ||||
Posted in reply to Cym13 | 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 |
Copyright © 1999-2021 by the D Language Foundation