How to change IEnumerable<byte> to String - c#

I have the following simplified function:
private IEnumerable<byte> Encode(IEnumerable<byte> Input)
{
computation();
return result;
}
The Buffer:
byte[] BufferHex = {0x00};
IEnumerable<byte> result1;
richtext.AppendText(Encoding.UTF8.GetString(result1));
The error is at the last line saying: Conversion IEnumerable to byte[] not possible.
I have tried several things but still no success. Any help will be appreciated.

As it says it is expecting a byte[] as parameter, so you need to convert your IEnumerable<byte> to a byte[], you can do this using ToArray extension method:
richtext.AppendText(Encoding.UTF8.GetString(result1.ToArray()));

Encoding.UTF8.GetString() expects a parameter of type byte[], not IEnumerable<byte>. So simply change that line to
richtext.AppendText(Encoding.UTF8.GetString(result1.ToArray()));
ToArray() is a LINQ extension that converts an IEnumerable<T> into a T[].

I don't know if this will be suitable for your case, but you can use Convert.ToBase64String(byte[] bytes) and don't forget to call ToArray(), on your enumerable

Related

How can I pass a byte value in c# function [duplicate]

This question already has answers here:
All possible array initialization syntaxes
(19 answers)
Closed 5 years ago.
I have this function in c#:
public string CommitDocument(string extension, byte[] fileBytes)
{
// some code here
}
I'm trying to call this function like this:
CommitDocument("document.docx", byte [1493]);
I'm getting an error: "Invalid expression term 'byte'". How can I pass a value to the parameter of type byte?
The byte[] is an array of bytes and you need to allocate the array first with 'new'.
byte[] myArray = new byte[1493];
CommitDocument("document.docx", myArray);
You defined CommitDocument as taking a byte array. A single byte is not convertible into a byte array. Or at least the Compiler is not doing that implicitly. There are a few ways around that limitation:
Provide a overload that takes a byte and makes it into a one element array:
public string CommitDocument(string extension, byte fileByte)
{
//Make a one element arry from the byte
var temp = new byte[1];
temp[0] = fileByte;
//Hand if of to the existing code.
CommitDocument(extension, temp);
}
Otherwise turn fileBytes in a Params Parameter. You can provide any amount of comma seperated bytes to a Params, and the compiler will automagically turn them into an array. See Params Documentation for details and limits:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/params

Convert part of List<string> to byte[]

List<string> K = new List<string>();
byte[] tmp = K[i >> 3].SelectMany(s => Encoding.Default.GetBytes(s)).ToArray();
I tying to convert, but there is an error:
The best overloaded method match for 'System.Text.Encoding.GetString(byte[])' has some invalid arguments
How correctly do this?
I'm not sure what you expect the call to K[i >> 3] to do. Your title says "convert part of a List", but what it does is simply return one string out of your List<string>.
Next, you call SelectMany() on that string. Since string is an IEnumerable<char>, the SelectMany call tries to call Encoding.Default.GetBytes() on each char in the string and return the resulting byte[] returned from each call into a combined IEnumerable<byte>. This fails, because Encoding.Default.GetBytes() expects a string parameter, not a char.
Based on your title, I expect that you expected K[i >> 3] to return an IEnumerable<string> containing a subset of your original List<string>. If it did, your code would make sense - SelectMany would pass each string in the subset to GetBytes, which would return a byte[], which would be concatenated to a larger IEnumerable<byte> containing the bytes for all the strings in the subset. But you need to fix your root cause, the subset-selection, for that to work.

Problems with an overloaded function inside a Generic Function

I am writing a function to help serialize data to pass through a socket. I wanted to write a small function that would serialize one item.
private byte[] SerializeOne<T>(T data)
{
byte[] oneItem = new byte[Constants.ONE_ITEM_BUFFER];
oneItem = BitConverter.GetBytes(data);
if (BitConverter.IsLittleEndian)
oneItem.Reverse();
return oneItem; }
The problem is BitConverter alwaysassumes data is a type bool and throws this error: Argument 1 cannot convert from T to bool. Am I missing some syntax to force BitConverter to use the T type or is this not possible in C#?

Passing both List and Array as argument of IEnumerable

I want to make a method that can accept both List<byte> and array of bytes as argument (as Resharper suggested):
public static UInt16 GetSourceAddress(IEnumerable<byte> packet)
{
return BitConverter.ToUInt16(new[] {packet[4], packet[5]}, 0);
}
Bute I get the follwing compilation error:
Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable<byte>'
I know I can just go ahead with two overloads with List and byte[], but what does this problem indicates? How to resolve it?
If you want random access, use IList<T> instead:
public static UInt16 GetSourceAddress(IList<byte> packet)
Both List<byte> and byte[] implement IList<byte>, and it has an indexer.
Try this
public static UInt16 GetSourceAddress(IEnumerable<byte> packet){
return BitConverter.ToUInt16(new[] {packet.ElementAt(4), packet.ElementAt(5)}, 0);
}

C# Convert to Byte Array

How can i convert this VBNet code into C#? (ByteToImage is a User Defined Function use to convert Byte Array into Bitmap.
Dim Bytes() As Byte = CType(SQLreader("ImageList"), Byte())
picStudent.Image = jwImage.ByteToImage(Bytes)
I tried
byte[] Bytes = Convert.ToByte(SQLreader("ImageList")); // Error Here
picStudent.Image = jwImage.ByteToImage(Bytes);
but it generates an error saying: Cannot implicitly convert type 'byte' to 'byte[]'
What i am doing is basically converting an Image from database to byte array and displaying it on the picturebox.
byte[] Bytes = (byte[]) SQLreader("ImageList");
picStudent.Image = jwImage.ByteToImage(Bytes);
Try this
byte[] Bytes = (byte[])SQLreader("ImageList");
Hope this helps
The problem is you have an array of bytes (byte[] in C# and Byte() in VB.Net) but the Convert.ToByte call just returns a simple byte. To make this work you need to cast the return of SQLreader to byte[].
There is no perfect analogous construct for CType in C# but a simple cast here should do the trick
byte[] Bytes = (byte[])SQLreader("ImageList");
CType is the equivalent of a type cast, not an actual conversion.Besides, Convert.ToByte tries to convert its input to a single byte, not an array. The equivalent code is
byte[] bytes=(byte[])SQLreader("ImageList");

Categories