Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get single byte from int

Tags:

c#

binary

I got an int number. For example 5630(decimal). The number in binary is:

00000000 00000000 00010101 11111110

I want to get the second byte in decimal (00010101). How do I get it?

like image 337
user2320928 Avatar asked Aug 31 '25 01:08

user2320928


2 Answers

You can use BitConverter.GetBytes():

int intValue = 5630;
byte[] intBytes = BitConverter.GetBytes(intValue);
byte result = intBytes[1];  // second least-significant byte

or just bit-shift 8 places to the right and convert to a byte (truncating the left bits):

((byte)(intValue >> 8))
like image 182
D Stanley Avatar answered Sep 02 '25 15:09

D Stanley


do a bitwise And with 00000000 00000000 11111111 00000000
(in hex, 0xFF00), and right shift by 8 places.

  var x = 5630;
  var secondByte = (x & 0xFF00) >> 8;

or, bit-shift first and strip off higher order bytes by &-ing with value
00000000 00000000 00000000 11111111
decimal 255, or (hex 0xFF)

  var x = 5630;
  var secondByte = (x >> 8) & 0xFF;
like image 24
Charles Bretana Avatar answered Sep 02 '25 13:09

Charles Bretana