What is the difference between byte and sbyte in C#?

In this tutorial, we will learn about the difference between byte and sbyte in C#. By IncludeHelp Last updated : April 04, 2023

byte

A single byte can store 8-bits value. Both are used for byte type of data i.e., the data that contains an only 1-byte value. The 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

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

Differences between byte and sbyte

In C#, both byte and sbyte are used to specify a single byte data. The main difference between byte and sbyte is that byte specifies unsigned values from 0 to 255, while sbyte specifies signed values from -128 to +127.

byte sbyte
byte stands for unsigned byte. sbyte stands for signed byte.
It can store positive bytes only. It can store negative and positive bytes.
It takes 8-bits space in the memory. It also takes the 8-bits in the memory.
Its data range is 0 to 255 that means it can store a minimum value 0 and maximum upto 255. Its data range is -128 to 127 that means it can store a minimum value -128 and maximum upto 127.
Declaration syntax:
byte variable;
Declaration syntax:
sbyte variable;

C# example to demonstrate the differences between byte and sbyte

Declaring signed and unsigned byte variable, assigning them with the values and printing the values.

using System;
using System.Text;

namespace ConsoleApplication3 {
  class Program {
    static void Main(string[] args) {
      byte a;
      sbyte b;

      //printing minimum & maximum values
      Console.WriteLine("Minimum value of byte: " + byte.MinValue);
      Console.WriteLine("Maximum value of byte: " + byte.MaxValue);

      Console.WriteLine("Minimum value of sbyte: " + sbyte.MinValue);
      Console.WriteLine("Maximum value of sbyte: " + sbyte.MaxValue);
      a = 0;
      Console.WriteLine("a = " + a);
      a = 255;
      Console.WriteLine("a = " + a);

      b = -100;
      Console.WriteLine("b = " + b);

      b = 123;
      Console.WriteLine("b = " + b);

      b = 127;
      Console.WriteLine("b = " + b);

      //hit ENTER to exit
      Console.ReadLine();
    }
  }
}

Output

Minimum value of byte: 0
Maximum value of byte: 255
Minimum value of sbyte: -128
Maximum value of sbyte: 127
a = 0
a = 255
b = -100
b = 123
b = 127



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.