12

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'.

4
  • 2
    Why not just cast it to byte ? Commented Jun 25, 2012 at 12:09
  • 1
    @V4Vendetta: Will it work, I read somewhere if the value is out of range, that is negative on sbyte, will throw exception. Commented Jun 25, 2012 at 12:19
  • Well not really say its -1 then you would get it as 255 Commented Jun 25, 2012 at 12:23
  • @V4Vendetta is right, you don't need unchecked for casting runtime variables. See my answer for the full details. Commented Mar 15, 2013 at 13:57

4 Answers 4

21

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.

Sign up to request clarification or add additional context in comments.

Comments

5
unchecked { sbyte s; s= (sbyte)"your value"; byte b=(byte)s; } 

More about unchecked is here

Comments

5

like this:

sbyte sb = 0xFF; byte b = unchecked((byte)sb); 

Comments

5
unchecked { sbyte s = (sbyte)250; //-6 (11111010) byte b = (byte)s; //again 250 (11111010) } 

2 Comments

Added clarification, what is meant by unchecked as used here?
Since 250 exceeds the range of sbyte(-128 - 127) an unchecked conversion is needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.