1

I am reversing a source code of a file writer, and here are the methods that read/write ints (or rather ushorts):

        BinaryReader _Reader;
        BinaryWriter _Writer;

        void RawWriteInt16(int value)
        {
            byte a = (byte)(value & 255);
            byte b = (byte)(value >> 8 & 255);
            _Writer.Write(a);
            _Writer.Write(b);
        }
        ushort RawReadUInt16()
        {
            int num = _Reader.ReadByte();
            int num2 = _Reader.ReadByte();
            return (ushort)((num2 << 8) + num);
        }

So, can you explain why the & with 255(11111111) which is always the same and the shifting?

P.S. I need this for an article and will give you credit. You can check it here if you like, or on codeproject: Sequential-byte-serializer

Thanks for the interest. Credits have been given to @Sentry and @Rotem. I will post also the codeproject url when the article gets approved

1 Answers1

6

That code turns a 16-bit integer value into two (8-bit) byte values:

## byte a = (byte)(value & 255); ##

(int)value:    1101 0010 0011 1000
(int)  255:    0000 0000 1111 1111
 bitwise &:    0000 0000 0011 1000
   to byte:              0011 1000

and then

## byte b = (byte)(value >> 8 & 255); ##

(int)value:    1101 0010 0011 1000
      >> 8:    0000 0000 1101 0010 
(int)  255:    0000 0000 1111 1111
 bitwise &:    0000 0000 1101 0010
   to byte:              1101 0010

So you have two bytes that represent the higher and lower part of a 16-bit int

Sentry
  • 4,102
  • 2
  • 30
  • 38
  • One could argue that the `&` is redundant as casting to `byte` already takes only the low order bits – Rotem Jun 24 '18 at 14:34
  • @Rotem You are right (https://stackoverflow.com/questions/7575643/what-happens-when-you-cast-from-short-to-byte-in-c), but maybe the author of the code wasn't aware of this or he wanted to make it explicitly clear – Sentry Jun 24 '18 at 14:36
  • Now I'm curious if the compiler omits the `&` from the IL. – Rotem Jun 24 '18 at 14:41
  • 2
    @Rotem This code is from ILSpy, so no: IL_0001: ldarg.1 IL_0002: ldc.i4 255 IL_0007: and IL_0008: conv.ovf.u1 IL_0009: stloc.0 – Nikolai Frolov Jun 24 '18 at 15:15