I have a function that want to receive sbyte* buffer how to create such in C# from scratch and from existing byte[]?
In C#, Byte Struct is used to represent 8-bit unsigned integers. The Byte is an immutable value type and the range of Byte is from 0 to 255. This class allows you to create Byte data types and you can perform mathematical and bitwise operations on them like addition, subtraction, multiplication, division, XOR, AND etc.
The SByte value type represents integers with values ranging from negative 128 to positive 127. Important. The SByte type is not CLS-compliant. The CLS-compliant alternative type is Int16. Byte can be used instead to replace a positive SByte value that ranges from zero to MaxValue.
To do this, we use the bitwise AND operator ( & ). We & the value present in each byte by 0xFF which is the hex (16 bit) notation for 255 . This way, we obtain the last 8 bits of our value.
// Allocate a new buffer (skip this if you already have one)
byte[] buffer = new byte[256];
unsafe
{
// The "fixed" statement tells the runtime to keep the array in the same
// place in memory (relocating it would make the pointer invalid)
fixed (byte* ptr_byte = &buffer[0])
{
// Cast the pointer to sbyte*
sbyte* ptr_sbyte = (sbyte*) ptr_byte;
// Do your stuff here
}
// The end of the "fixed" block tells the runtime that the original array
// is available for relocation and/or garbage collection again
}
Casting to Array and then casting to byte[] will be enough.
byte[] unsigned = { 0, 1, 2 };
sbyte[] signed = (sbyte[]) (Array)unsigned;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With