Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to turn byte[] into sbyte* in C#?

I have a function that want to receive sbyte* buffer how to create such in C# from scratch and from existing byte[]?

like image 771
Rella Avatar asked Aug 22 '10 21:08

Rella


People also ask

What is a byte [] in C#?

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.

What is SByte type?

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.

How to Convert an integer into a specific byte array in c++?

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.


2 Answers

// 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
}
like image 56
Timwi Avatar answered Oct 31 '22 08:10

Timwi


Casting to Array and then casting to byte[] will be enough.

byte[] unsigned = { 0, 1, 2 };

sbyte[] signed = (sbyte[]) (Array)unsigned;

like image 41
Gus Avatar answered Oct 31 '22 08:10

Gus