Encoding used in cast from char to byte

前端 未结 3 552
死守一世寂寞
死守一世寂寞 2020-12-18 01:37

Take a look at the following C# code (function extracted from the BuildProtectedURLWithValidity function in http://wmsauth.org/examples):

byte[]         


        
3条回答
  •  鱼传尺愫
    2020-12-18 02:25

    char represents a 16-bit UTF-16 code point. Casting a char to a byte results in the lower byte of the character, but both Douglas and dan04 are wrong in that it will always quietly discard the higher byte. If the higher byte is not zero the result depends on whether the compiler option Check for arithmetic overflow/underflow is set:

    using System;
    namespace CharTest
    {
        class Program
        {
            public static void Main(string[] args)
            {   ByteToCharTest( 's' );
                ByteToCharTest( 'ы' );
    
                Console.ReadLine();
            }
    
            static void ByteToCharTest( char c )
            {   const string MsgTemplate =
                    "Casting to byte character # {0}: {1}";
    
                string msgRes;
                byte   b;
    
                msgRes = "Success";
                try
                {   b = ( byte )c;  }
                catch( Exception e )
                {   msgRes = e.Message;  }
    
                Console.WriteLine(
                    String.Format( MsgTemplate, (Int16)c, msgRes ) );
            }
        }
    }
    

    Output with overflow checking:

    Casting to byte character # 115: Success
    Casting to byte character # 1099: Arithmetic operation resulted in an overflow.
    

    Output without overflow checking:

    Casting to byte character # 115: Success        
    Casting to byte character # 1099: Success
    

提交回复
热议问题