Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the GetBytes function work?

I wrote my own class which converts C# standard primitives into byte arrays.

Later on, I took a look at the BitConverter class source, to see how pros did it.

My code example:

public static byte[] getBytes(short value) {
    byte[] bytes = new byte[2];

    bytes[0] = (byte)(value >> 8);
    bytes[1] = (byte)value;

    return bytes;
}

BitConverter class code:

public unsafe static byte[] GetBytes(short value) 
{ 
    byte[] bytes = new byte[2];
    fixed(byte* b = bytes) 
        *((short*)b) = value;
    return bytes;
}

Why are their functions tagged as unsafe and use fixed operator?

Are such functions error prone even if they use unsafe? Should I just drop mine and use their implementation? Which is more efficient?

like image 300
Scavs Avatar asked Aug 15 '15 11:08

Scavs


People also ask

What does getBytes function do?

getbytes() function in java is used to convert a string into a sequence of bytes and returns an array of bytes.

How do you use getBytes?

The getBytes() method encodes a given String into a sequence of bytes and returns an array of bytes. The method can be used in below two ways: public byte[] getBytes(String charsetName) : It encodes the String into sequence of bytes using the specified charset and return the array of those bytes.

What is getBytes in C#?

GetBytes() method converts a string into a bytes array. The following code example converts a C# string into a byte array in Ascii format and prints the converted bytes to the console. The Encoding. GetString() method converts an array of bytes into a string.

What is getBytes utf8?

UTF stands for Unicode Transformation Format. The '8' signifies that it allocates 8-bit blocks to denote a character. The number of blocks needed to represent a character varies from 1 to 4. In order to convert a String into UTF-8, we use the getBytes() method in Java.


1 Answers

Yes, drop yours and use the standard library.

It is more efficient, because it copies both bytes at once by casting the byte array to a short pointer. To do this it requires fixed to allow the use of pointers, and hence the unsafe keyword.

Unsafe code is generally to be avoided in your own assemblies, as it means your code cannot be guaranteed safe, and so can only be run in fully trusted environments.

However, since Bitconverter is part of the standard .Net assemblies that are signed by Microsoft, Windows knows they are ok.

Library functions are less error prone too, because they have been battle hardened by millions of developers using them every day, whereas your function has been tested only by you.

like image 78
GazTheDestroyer Avatar answered Oct 04 '22 23:10

GazTheDestroyer