Is unsafe normal in .net C#? - c#

I need do create a new instance of String from the array of sbytes (sbyte[]).
For that I need to convert sbyte[] into sbyte*
It is possible only using unsafe keyword.
is that okay or is there any other ways to create a String from array of sbytes?

First:
How to convert a sbyte[] to byte[] in C#?
sbyte[] signed = { -2, -1, 0, 1, 2 };
byte[] unsigned = (byte[]) (Array)signed;
Then:
string yourstring = UTF8Encoding.UTF8.GetString(unsigned);

Why are you using sbyte?
Encoding.Default.GetString() (and any other encoding) takes a byte[] Array as argument, so you could convert the sbyte[] Array using LINQ if all values are non-negative: array.Cast<byte>().ToArray().

Related

Is there C# `Encoding.UTF8.GetString` equivalent in C++?

Is there C# Encoding.UTF8.GetString equivalent in C++ ? Or another fast way parse byte array containing the sequence of bytes and decode to string.
You can try this:
auto *wstrBytes = new wchar_t[size];
memcpy_s(wstrBytes , size, rawBytes, size);
std::wstring unicodeStr(wstrBytes , size);
delete [] wstrBytes;

How to convert C# Struct to Byte Array

I have a structure which I want to send to a TCP client throught TCP protocol so I want to assign or copy this struct data to byte array:
struct StartReadXML
{
public int CmdID;//3
public char[] CmdName;//ReadXML
public char[] Description;//Other data
};
here am assigning data to struct data members as below :
StartReadXML startXML=new StartReadXML();
startXML.CmdID = 3;
startXML.CmdName = "sreedhar".ToCharArray();
startXML.Description = "Kumar".ToCharArray();
Now, I want it to be assigned to a byte array. Which am doing using marshalling as below:
int sizestartXML = Marshal.SizeOf(startXML);//Get size of struct data
byte[] startXML_buf = new byte[sizestartXML];//byte array & its size
IntPtr ptr = Marshal.AllocHGlobal(sizestartXML);//pointer to byte array
Marshal.StructureToPtr(startXML, ptr, true);
Marshal.Copy(ptr, startXML_buf, 0, sizestartXML);
Marshal.FreeHGlobal(ptr);
//Sending struct data packet
stm.Write(startXML_buf, 0, startXML_buf.Length);//Modified
But, it fails at Structuretoptr conversion method. Please help in transferring the struct data as bytes for which am using above steps.
Thanks in advance Smile | :) !!
You cannot call StructureToPtr on arrays of variable size.
What this boils down to is that unless you know the size of CmdName and declare it - if it would be for example, 20 chars in size, like so:
public fixed char[] CmdName[20];
You will be greeted with an exception from the Marshal saying that your structure is either non-blittable or no meaningful size can be obtained.
This is a requirement the CLR imposes, and you can not work around.
An alternative method would be to use the Convert class or a serializer to convert the members of your struct manually, but unless you know the size of those arrays up front, you won't be able to use StructureToPtr - the same goes for the string type, as I'm assuming that's what your char array will contain.
Consider using a MemoryStream and writing values to the stream, and sending the contents of the stream using stream.ToArray() instead.
Considering that you can't simply convert to binary a struct, use for example:
class StartReadXML
{
public int CmdID;//3
public string CmdName;//ReadXML
public string Description;//Other data
}
Then:
var srx = new StartReadXML();
srx.CmdID = 3;
srx.CmdName = "sreedhar";
srx.Description = "Kumar";
// Example of how to Write to byte[] buffer
byte[] buffer;
using (var ms = new MemoryStream())
{
using (var bw = new BinaryWriter(ms, Encoding.UTF8))
{
bw.Write(srx.CmdID);
bw.Write(srx.CmdName);
bw.Write(srx.Description);
}
buffer = ms.ToArray();
}
// Example of how to Read from byte[] buffer
var srx2 = new StartReadXML();
using (var ms = new MemoryStream(buffer))
{
using (var br = new BinaryReader(ms, Encoding.UTF8))
{
srx2.CmdID = br.ReadInt32();
srx2.CmdName = br.ReadString();
srx2.Description = br.ReadString();
}
}
Note that here I'm working with a "variable length" packet: the length of CmdName and Description aren't fixed (and BinaryWriter/BinaryReader handle this by prepending the length of the string).
The opposite is when you have a packet of fixed length, with fixed-length strings. That requires a totally different handling.

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");

In C# how can I truncate a byte[] array

I have a byte[] array of one size, and I would like to truncate it into a smaller array?
I just want to chop the end off.
Arrays are fixed-size in C# (.NET).
You'll have to copy the contents to a new one.
byte[] sourceArray = ...
byte[] truncArray = new byte[10];
Array.Copy(sourceArray , truncArray , truncArray.Length);
You could use Array.Resize, but all this really does is make a truncated copy of the original array and then replaces the original array with the new one.
private static void Truncate() {
byte[] longArray = new byte[] {1,2,3,4,5,6,7,8,9,10};
Array.Resize(ref longArray, 5);//longArray = {1,2,3,4,5}
//if you like linq
byte[] shortArray = longArray.Take(5).ToArray();
}
I usually create an extension method:
public static byte[] SubByteArray(this byte[] byteArray, int len)
{
byte[] tmp = new byte[len];
Array.Copy(byteArray, tmp, len);
return tmp;
}
Which can be called on the byte array easily like this:
buffer.SubByteArray(len)
You can't truncate an array in C#. They are fixed in length.
If you want a data structure that you can truncate and acts like an array, you should use List<T>. You can use the List<T>.RemoveRange method to achieve this.
By the way, Array.Resize method takes much more time to complete. In my simple case, I just needed to resize array of bytes (~8000 items to ~20 items):
Array.Resize // 1728 ticks
Array.Copy // 8 ticks
You can now use ellipse notation in C#.
var truncArray = sourceArray[..10];

How can I convert sbyte[] to base64 string?

How can I convert sbyte[] to base64 string?
I cannot convert that sbyte[] to a byte[], to keep interoperability with java.
You absolutely can convert the sbyte[] to a byte[] - I can pretty much guarantee you that the Java code will really be treating the byte array as unsigned. (Or to put it another way: base64 is only defined in terms of unsigned bytes...)
Just convert to byte[] and call Convert.ToBase64String. Converting to byte[] is actually really easy - although C# itself doesn't provide a conversion between the two, the CLR is quite happy to perform a reference conversion, so you just need to fool the C# compiler:
sbyte[] x = { -1, 1 };
byte[] y = (byte[]) (object) x;
Console.WriteLine(Convert.ToBase64String(y));
If you want to have a genuine byte[] you can copy:
byte[] y = new byte[x.Length];
Buffer.BlockCopy(x, 0, y, 0, y.Length);
but personally I'd stick with the first form.
class Program
{
static void Main()
{
sbyte[] signedByteArray = { -2, -1, 0, 1, 2 };
byte[] unsignedByteArray = (byte[])(Array)signedByteArray;
Console.WriteLine(Convert.ToBase64String(unsignedByteArray));
}
}

Categories