February 07, 2018 Re: more OO way to do hex string to bytes conversion | ||||
---|---|---|---|---|
| ||||
Posted in reply to Craig Dillabaugh | On 07/02/2018 4:06 AM, Craig Dillabaugh wrote: > On Wednesday, 7 February 2018 at 03:25:05 UTC, rikki cattermole wrote: >> On 06/02/2018 8:46 PM, Craig Dillabaugh wrote: >>> On Tuesday, 6 February 2018 at 18:46:54 UTC, H. S. Teoh wrote: >>>> [...] >>> clip >>>> [...] >>> clip >>>> [...] >>> >>> Wouldn't it be more accurate to say OO is not the correct tool for every job rather than it is "outdated". How would one write a GUI library with chains and CTFE? >> >> But you could with signatures and structs instead ;) > > I am not sure how this would work ... would this actually be a good idea, or are you just saying that technically it would be possible? A very good idea :) WIP: https://github.com/rikkimax/DIPs/blob/master/DIPs/DIP1xxx-RC.md https://github.com/rikkimax/stdc-signatures/tree/master/stdc |
February 07, 2018 Re: more OO way to do hex string to bytes conversion | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ralph Doncaster | On Tuesday, 6 February 2018 at 18:33:02 UTC, Ralph Doncaster wrote: > I've been reading std.conv and std.range, trying to figure out a high-level way of converting a hex string to bytes. The only way I've been able to do it is through pointer access: > > import std.stdio; > import std.string; > import std.conv; > > void main() > { > immutable char* hex = "deadbeef".toStringz; > for (auto i=0; hex[i]; i += 2) > writeln(to!byte(hex[i])); > } > > > While it works, I'm wondering if there is a more object-oriented way of doing it in D. After a bunch of searching, I came across hex string literals. They are mentioned but not documented as a literal. https://dlang.org/spec/lex.html#string_literals Combined with the toHexString function in std.digest, it is easy to convert between hex strings and byte arrays. import std.stdio; import std.digest; void main() { auto data = cast(ubyte[]) x"deadbeef"; writeln("data: 0x", toHexString(data)); } p.s. the cast should probably be to immutable ubyte[]. I'm guessing without it, there is an automatic copy of the data being made. |
February 07, 2018 Re: more OO way to do hex string to bytes conversion | ||||
---|---|---|---|---|
| ||||
Posted in reply to Ralph Doncaster | On Wednesday, 7 February 2018 at 14:47:04 UTC, Ralph Doncaster wrote:
> p.s. the cast should probably be to immutable ubyte[]. I'm guessing without it, there is an automatic copy of the data being made.
No copy - you just get undefined behavior if you actually try to modify it!
|
Copyright © 1999-2021 by the D Language Foundation