What is the opposite of BitConverter.ToString(byte[]) ?

G

Greg Ennis

If I run the following code:

Byte[] bytes = System.Text.Encoding.ASCII.GetBytes("test");
return BitConverter.ToString(bytes);

I get the string "74-65-73-74" back. My question is, what is the
easiest way to convert the string back to "test"?

Can it be done without breaking the string and using a loop, etc.? I
have tried many methods, but can't find a way without using a loop. It
seems silly that the framework can go one direction but not the other.

Any help please?
 
C

Chris

System.Text.Encoding.ASCII.GetString(bytes);

i think that's what you're looking for.

Chris
 
J

Jon Skeet [C# MVP]

Chris said:
System.Text.Encoding.ASCII.GetString(bytes);

i think that's what you're looking for.

I don't think so - that certainly doesn't do the reverse of
BitConverter.ToString.

For me, BitConverter.ToString is really for debug purposes, to easily
see the values in a byte array. That's why (I believe) there's no
reverse method.
 
G

Greg Ennis

System.Text.Encoding.ASCII.GetString(bytes);

i think that's what you're looking for.

Thanks but this is not correct; this will give me a string of length 11
whereas I am looking for the original string of length 4. This is
because GetString() does not *decode* the hex values in the bytes.

So, I am still looking for a 1-step solution...

-Greg



*** Sent via Devdex http://www.devdex.com ***
Don't just participate in USENET...get rewarded for it!
 
C

Cablewizard

Greg,

I believe Jon is correct with his statement:
For me, BitConverter.ToString is really for debug purposes, to easily
see the values in a byte array. That's why (I believe) there's no
reverse method.

This will just give you a nice human readable representation of the bytes.

System.Text.Encoding.ASCII.GetBytes(string)
System.Text.Encoding.ASCII.GetString(bytes)
would be complimentary functions dealing with the underlying data.

Just like MyObject.ToString almost certainly would not give you a String from
which you could create an identical copy of your Object.

Gerald
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top