0

I've tried the following but it returns a weird string:

Encoding.Default.GetString(buffer);

Here's my byte array. I want to convert it to "8.31.99.141".

enter image description here

1
  • What does not work? What kind of string so you expect? Commented Mar 17, 2014 at 20:11

4 Answers 4

4

It appears that this is a misunderstanding. A byte's value does not directly relate to a string's character representation. That is to say that the byte 8 is not necessarily "8" in a string. The act of converting between bytes and characters is called Encoding.

You can test some encoding yourself:

var testString = "my test string";
var bytes = Encoding.Default.GetBytes(testString);
var confirmString = Encoding.Default.GetString(bytes);

To output the byte value directly as a string, use this:

var result = string.Join(".", bytes);

This will implicitly call .ToString() on the bytes, which returns the byte value as a string. Note that this is MUCH different than encoding.

Sign up to request clarification or add additional context in comments.

2 Comments

I think he wants the numeric representation of each byte and not it's encoded value.
@Kevin - I did update my answer to reflect this as well.
3

It seems you need String.Join :

string result = String.Join(".", lol);

4 Comments

Not sure why this had a downvote: it is perfectly fine
@Crono String.Join also takes an array of Object
@Crono: Time to read the docs... can take an IEnumerable<T>: msdn.microsoft.com/en-us/library/dd992421%28v=vs.110%29.aspx
0
String.Join(".", buffer.ToList().Select(i=>i.ToString()));

1 Comment

everything after buffer is redundant and undesirable; the extra list, the iterator, the delegate, etc
0

If your buffer length may differ:

var result = string.Join(".", buffer);

If length is always fixed to four (like for an IP adress for example), this reads better IMHO:

var result = string.Format("{0}.{1}.{2}.{3}", buffer);

Of course this is assuming you want the string representation of each individual byte.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.