bytes To Hex

  • Thread starter Thread starter Analizer1
  • Start date Start date
A

Analizer1

Hi I have a Long Number
In a Byte[]

Im not sure how to convert this Byte[] array to a Hex
string

thanks
 
Hi I have a Long Number
In a Byte[]

Im not sure how to convert this Byte[] array to a Hex
string

Well, the .NET way would be to use BitConverter to get the bytes into an
actual long value, and then use ToString("x") to convert to hex:

byte[] rgb = { 1, 2, 3, 4, 5, 6, 7, 8 };
string strHex = BitConverter.ToInt64(rgb, 0).ToString("x");

Pete
 
Thanks alot


Hi I have a Long Number
In a Byte[]

Im not sure how to convert this Byte[] array to a Hex
string

Well, the .NET way would be to use BitConverter to get the bytes into an
actual long value, and then use ToString("x") to convert to hex:

byte[] rgb = { 1, 2, 3, 4, 5, 6, 7, 8 };
string strHex = BitConverter.ToInt64(rgb, 0).ToString("x");

Pete
 
Peter Duniho skrev:
Hi I have a Long Number
In a Byte[]

Im not sure how to convert this Byte[] array to a Hex
string

Well, the .NET way would be to use BitConverter to get the bytes into an
actual long value, and then use ToString("x") to convert to hex:

byte[] rgb = { 1, 2, 3, 4, 5, 6, 7, 8 };
string strHex = BitConverter.ToInt64(rgb, 0).ToString("x");

Pete

Or as simple as strHex = BitConverter.ToString(rgb);

It depends on how you want to present the result, - this one puts a
whitespace between each hex pair, - great when debugging.
 
You can also call the ToString() directly in the byte variable:



byte[] ba = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 255 };

foreach(byte b in ba)
{
string hex = b.ToString("X");
Console.WriteLine( (hex.Length == 1 ? "0" : "") + hex );
}

Console.Read();
 
Rene said:
You can also call the ToString() directly in the byte variable:



byte[] ba = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 255 };

foreach(byte b in ba)
{
string hex = b.ToString("X");
Console.WriteLine( (hex.Length == 1 ? "0" : "") + hex );
}

If you're going to do that, you might as well use the format specifier
to get the length right:

string hex = b.ToString("X2");
Console.WriteLine(hex);
 
Hi I have a Long Number
In a Byte[]
[...]

Or as simple as strHex = BitConverter.ToString(rgb);

That's incorrect.

The OP specifically said he's got data that should be interpreted as a
long. Your suggestion won't treat the data as a long.
It depends on how you want to present the result, - this one puts a
whitespace between each hex pair, - great when debugging.

But not so good when you want to display a 64-bit integer in hexadecimal.

BTW, it also doesn't put whitespace between hex pairs. It puts hyphens.

Pete
 
You can also call the ToString() directly in the byte variable:

byte[] ba = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 255 };

foreach(byte b in ba)
{
string hex = b.ToString("X");
Console.WriteLine( (hex.Length == 1 ? "0" : "") + hex );
}

Console.Read();

And in addition to what Jon wrote, the above code again does not display
an array containing a 64-bit integer. It simply emits a series of bytes
as hexadecimal pairs.

Heck, the sample byte array isn't even a valid 64-bit integer. It's _two_
64-bit integers, at best.

Pete
 
My Byte[] array consists of DirectoryServices Users Sid from the domain

I needed to Convert Each Byte to a Hex String , Then Concatenate each
following byte

below is a example...is the proper way, or is there a better way of
accomplishing this

uint uDec;

for (int x = 0; x < aBytes.GetLength(0); x++)
{

uDec = Convert.ToUInt32(aBytes[x]);

sHexId.Append(String.Format("{0:x2}",uDec));

}
Console.WriteLine(sHexId);

//it matches the hex id Sql Returns



Tks



Hi I have a Long Number
In a Byte[]

Im not sure how to convert this Byte[] array to a Hex
string

Well, the .NET way would be to use BitConverter to get the bytes into an
actual long value, and then use ToString("x") to convert to hex:

byte[] rgb = { 1, 2, 3, 4, 5, 6, 7, 8 };
string strHex = BitConverter.ToInt64(rgb, 0).ToString("x");

Pete
 
Analizer1 said:
My Byte[] array consists of DirectoryServices Users Sid from the domain

I needed to Convert Each Byte to a Hex String , Then Concatenate each
following byte

below is a example...is the proper way, or is there a better way of
accomplishing this

uint uDec;

for (int x = 0; x < aBytes.GetLength(0); x++)
{
uDec = Convert.ToUInt32(aBytes[x]);
sHexId.Append(String.Format("{0:x2}",uDec));
}
Console.WriteLine(sHexId);

Well, a few points to note:

1) It's better style to declare variables as close to their use as
possible, so I'd declare uDec inside the loop rather than outside

2) I'd always use the Length property of an array instead of
GetLength(0)

3) When I don't care about the index, I use foreach instead of a for
loop

4) There's no need to convert to a uint to start with - just call
ToString on the byte...

5) ... or rather than formatting it and then appending it, use
AppendFormat


So, the resulting code would look something like:

StringBuilder builder = new StringBuilder(aBytes.Length*2);
foreach (byte b in aBytes)
{
builder.AppendFormat("{0:x2}", b);
}
Console.WriteLine (builder.ToString());
 
My Byte[] array consists of DirectoryServices Users Sid from the domain

I needed to Convert Each Byte to a Hex String , Then Concatenate each
following byte

below is a example...is the proper way, or is there a better way of
accomplishing this

uint uDec;

for (int x = 0; x < aBytes.GetLength(0); x++)
{

uDec = Convert.ToUInt32(aBytes[x]);

sHexId.Append(String.Format("{0:x2}",uDec));

}
Console.WriteLine(sHexId);

//it matches the hex id Sql Returns

If the code you posted provides the results you expected, then the "long"
in your byte array is big-endian (i.e. not in the same format that an
Intel-based .NET implementation would use). Since BitConverter only works
with little-endian, you'd either need a different bit-conversion class (if
I recall correctly, Jon Skeet's utility library includes one) or do it
manually as you've done.

Assuming that's the case, then the code you posted is reasonable, though
not what I'd write. I would use:

string sHexId = "";
foreach (byte b in aBytes)
{
sHexId += b.ToString("x2");
}

There's no need to convert the byte to UInt32 first, nor do you need to
call the String class's Format() method. Of course, you may want to
include a check in the code to ensure that the byte array is always 8
bytes long. Both your example and mine assume it is, and won't produce
correct results if it's not.

Pete
 
Analizer1 said:
My Byte[] array consists of DirectoryServices Users Sid from the domain

I needed to Convert Each Byte to a Hex String , Then Concatenate each
following byte

below is a example...is the proper way, or is there a better way of
accomplishing this

uint uDec;

for (int x = 0; x < aBytes.GetLength(0); x++)
{

uDec = Convert.ToUInt32(aBytes[x]);

sHexId.Append(String.Format("{0:x2}",uDec));

}
Console.WriteLine(sHexId);
This works, but it's horribly inefficient. Of course, as long as you don't
need to do it a few hundred times every second, it doesn't matter. And even
if you do, this function probably won't be the bottleneck. Still, if you do
need this to be fast...

const string hexDigits = "0123456789abcdef";

int bl = aBytes.Length;
char[] result = new char[bl * 2];
for (int n = 0; n != bl; ++n) {
result[n * 2 + 0] = hexDigits[aBytes[n] / 16];
result[n * 2 + 1] = hexDigits[aBytes[n] % 16];
}
Console.WriteLine(new string(result));

This approach is over 50 times faster than yours. If you don't like to spend
that much keystrokes on it, even this oneliner is better (better still than
doing it yourself with a StringBuilder):

Console.WriteLine(BitConverter.ToString(aBytes).Replace("-","");

Avoid String.Format() and its relatives in tight loops. If you need to do
positional replacement or locale-dependent formatting they're well worth it
(it's much more readable than gluing strings together yourself) but for
trivial conversions like these, repeated in a loop, they're not good.
 
ah, I didn't paid attention to the "Hi I have a *Long *Number"..... such a
small oversight :)



I thought that all he wanted to do was to show hex of a byte array.



This is not the first time nor the last time I will make such mistakes!!



Cool info about the "X2" format.



You can also call the ToString() directly in the byte variable:

byte[] ba = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 255 };

foreach(byte b in ba)
{
string hex = b.ToString("X");
Console.WriteLine( (hex.Length == 1 ? "0" : "") + hex );
}

Console.Read();

And in addition to what Jon wrote, the above code again does not display
an array containing a 64-bit integer. It simply emits a series of bytes
as hexadecimal pairs.

Heck, the sample byte array isn't even a valid 64-bit integer. It's _two_
64-bit integers, at best.

Pete
 
this was my 1st Run at this type of conversion...
so your remarks are welcome...

I Want The Fastest and Tightest Conversion Possible

Tks

Jeroen Mostert said:
Analizer1 said:
My Byte[] array consists of DirectoryServices Users Sid from the domain

I needed to Convert Each Byte to a Hex String , Then Concatenate each
following byte

below is a example...is the proper way, or is there a better way of
accomplishing this

uint uDec;

for (int x = 0; x < aBytes.GetLength(0); x++)
{

uDec = Convert.ToUInt32(aBytes[x]);

sHexId.Append(String.Format("{0:x2}",uDec));

}
Console.WriteLine(sHexId);
This works, but it's horribly inefficient. Of course, as long as you don't
need to do it a few hundred times every second, it doesn't matter. And
even if you do, this function probably won't be the bottleneck. Still, if
you do need this to be fast...

const string hexDigits = "0123456789abcdef";

int bl = aBytes.Length;
char[] result = new char[bl * 2];
for (int n = 0; n != bl; ++n) {
result[n * 2 + 0] = hexDigits[aBytes[n] / 16];
result[n * 2 + 1] = hexDigits[aBytes[n] % 16];
}
Console.WriteLine(new string(result));

This approach is over 50 times faster than yours. If you don't like to
spend that much keystrokes on it, even this oneliner is better (better
still than doing it yourself with a StringBuilder):

Console.WriteLine(BitConverter.ToString(aBytes).Replace("-","");

Avoid String.Format() and its relatives in tight loops. If you need to do
positional replacement or locale-dependent formatting they're well worth
it (it's much more readable than gluing strings together yourself) but for
trivial conversions like these, repeated in a loop, they're not good.
 
Analizer1 said:
this was my 1st Run at this type of conversion...
so your remarks are welcome...

I Want The Fastest and Tightest Conversion Possible

Why, out of interest? Just how many of these are you doing? Do you have
specific performance goals in mind? If you're getting the data from
directory services, that's likely to be much, much slower than any of
the conversion mechanisms given here.

It's always worth working out where performance really matters - and
I'd be very surprised if the conversion here ended up being a real
bottleneck.
 
Thanks for all your Responses
I will work with your examples

Mine was just the 1st run at converting The Directoryservices User SID to a
Hex String

Thank you very much
 
Why, out of interest? Just how many of these are you doing? Do you have
specific performance goals in mind? If you're getting the data from
directory services, that's likely to be much, much slower than any of
the conversion mechanisms given here.

Agreed. Jeroen's version is an interesting exercise, but it should almost
never be the case that one would actually need code written like that.

Writing code that's comparatively difficult to understand like that is
only something you should do once you've tried a readable version and
found it to be _the_ bottleneck performance-wise.

Pete
 
ah, I didn't paid attention to the "Hi I have a *Long *Number"..... such
a
small oversight :)

I thought that all he wanted to do was to show hex of a byte array.

Well, for what it's worth, it turns out his original question was
inaccurate. So you weren't actually far off after all. :)
This is not the first time nor the last time I will make such mistakes!!

Been there, done that. :)

Pete
 
Oh dear. I sort of figured that would happen. But really, you probably don't.
Agreed. Jeroen's version is an interesting exercise, but it should
almost never be the case that one would actually need code written like
that.
I know I was being evil by talking about fast code for that (since people
get obsessed with "the fastest code" too easily), but I couldn't help
myself. I did point out that it's highly unlikely that formatting hexstrings
would be a bottleneck for anything. For one thing, you will presumably want
to *send* those hexstrings somewhere, and then you run smack-dab into I/O,
which tends to bottleneck a lot more.
Writing code that's comparatively difficult to understand like that is
only something you should do once you've tried a readable version and
found it to be _the_ bottleneck performance-wise.
Now here's where I'm slightly offended at the suggestion of producing
unreadable code. Most C programmers would agree that my version is a paragon
of readability. :-D

Also, my comment on not using String.Format() in loops if it's obvious to
avoid still stands (and in this case, using BitConverter is pretty obvious,
and fast to boot as a bonus). Extensive string manipulation *can* become a
bottleneck fairly quickly, or even just a noticeable drag, and StringBuilder
isn't a cure-all for string performance problems.
 
[...]
I know I was being evil by talking about fast code for that (since
people get obsessed with "the fastest code" too easily), but I couldn't
help myself. I did point out that it's highly unlikely that formatting
hexstrings would be a bottleneck for anything.

That's true. :) I didn't mean to imply that you yourself were suggesting
such code would be useful here.
Now here's where I'm slightly offended at the suggestion of producing
unreadable code. Most C programmers would agree that my version is a
paragon of readability. :-D

Uh. Sure. :)
Also, my comment on not using String.Format() in loops if it's obvious
to avoid still stands (and in this case, using BitConverter is pretty
obvious, and fast to boot as a bonus). Extensive string manipulation
*can* become a bottleneck fairly quickly, or even just a noticeable
drag, and StringBuilder isn't a cure-all for string performance problems.

I wouldn't suggest using StringBuilder in this case anyway. You've got a
finite well-defined string length to deal with and I doubt there's a
significant performance difference between the two. Just appending String
instances eight times is probably fine, even though it does result in a
much larger number of data copies.

I disagree that there's anything wrong with using some sort of formatting
in a loop here. Sure, you can make that specific section of code perform
much better by using a lookup table to generate digits. But that is only
useful if that specific section of code is where you spend the bulk of
your time. I think we all agree that's not likely to be the case here.

Rules like "don't format strings in loops" just leads to difficult-to-read
code (C programmers notwithstanding :) ). It's not a good rule, because
there are so many good exceptions to it.

Pete
 
Back
Top