Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting sbyte to byte

Tags:

c#

byte

bits

I have a variable of type sbyte and would like to copy the content to a byte. The conversion wouldn't be a value conversion, rather a bit per bit copy.

For example,

if mySbyte in bits is: '10101100', after conversion, the corresponding byte variable will also contain the bits '10101100'.

like image 330
Shamim Hafiz - MSFT Avatar asked Jun 25 '12 12:06

Shamim Hafiz - MSFT


People also ask

How to Convert SByte to byte in c#?

Since both byte and sbyte have the same binary representation there's no need to copy the data. Just do a cast to Array, then cast it to byte[] and it'll be enough.

What is the difference between byte and Sbyte?

byte is used to work with unsigned byte data, it works with an only positive value between in the range of 0 to 255. sbyte is used to work with the signed byte data, it works with both types of data (Negative and Positive), it can store the between in the range of -128 to 127.

What is Sbyte data type?

The SByte value type represents integers with values ranging from negative 128 to positive 127.


1 Answers

Let me clarify the unchecked business. The MSDN page states that unchecked is used to prevent overflow checking, which would otherwise, when inside a checked context, give a compile error or throw an exception.

...IF inside a checked context.

The context is checked either explicitly:

checked { ... } 

or implicitly*, when dealing with compile-time constants:

byte b = (byte)-6; //compile error
byte b2 = (byte)(200 + 200); //compile error

int i = int.MaxValue + 10; //compiler error

But when dealing with runtime variables, the context is unchecked by default**:

sbyte sb = -6;
byte b = (byte)sb; //no problem, sb is a variable


int i = int.MaxValue;
int j = i + 10;    //no problem, i is a variable

To summarize and answer the original question:

Need byte<->sbyte conversion on constants? Use unchecked and cast:

byte b = unchecked( (byte) -6 );

Need byte<->sbyte conversion on variables? Just cast:

sbyte sb = -6;
byte b = (byte) sb;

* There is a third way to get a checked context by default: by tweaking the compiler settings. E.g. Visual Studio -> Project properties -> Build -> Advanced... -> [X] Check for arithmetic overflow/underflow

** The runtime context is unchecked by default in C#. In VB.NET for example, the default runtime context is CHECKED.

like image 188
Cristian Diaconescu Avatar answered Oct 03 '22 16:10

Cristian Diaconescu