My experience with C# is very very limited and a simple python program like the one I'm trying to convert is beyond my experience in C#. If anyone knows of any converters or is willing to help me out I would greatly appreciate it!

class ByteReader(object):
    """
    Reads bytes from a file.
    """
    def __init__(self, filename):
        self._buffer = list(bytearray(open(filename, 'rb').read()))
        self.pos = 0
        self._eof = EOFError('unexpected end of file')

    def read_byte(self):
        """Read one byte."""
        try:
            byte = self._buffer[self.pos]
            self.pos += 1
            return byte
        except IndexError:
            raise self._eof

    def peek_byte(self):
        """Return the next byte in the file.

        This can be used for look-ahead."""
        try:
            return self._buffer[self.pos]
        except IndexError:
            raise self._eof

    def peek_list(self, n):
        """Return a list of the next n bytes."""
        return self._buffer[self.pos:self.pos+n]

    def read_short(self):
        """Read short (2 bytes little endian)."""
        a, b = self.read_list(2)
        return a << 8 | b

    def read_long(self):
        """Read long (4 bytes little endian)."""
        a, b, c, d = self.read_list(4)
        return a << 24 | b << 16 | c << 8 | d

    def read_list(self, n):
        """Read n bytes and return as a list."""
        i = self.pos
        ret = self._buffer[i:i + n]
        if len(ret) < n:
            raise self._eof

        self.pos += n
        return ret

    def __enter__(self):
        return self

    def __exit__(self, type, value, traceback):
        return False

Recommended Answers

All 5 Replies

Hi Thanh Phong, welcome to DaniWeb :)
Why would you try to reinvent the wheel, when a class that does the job is readily available in C#? Read about BinaryReader class here

Another way is to use IronPython to create a .NET exe file.

There is an automated online conversion tool you can try here:

https://pythoncsharp.com/

I think you know what to expect with an automated conversion. It will probably not compile but will be valid syntax, which is a good enough basis for a manual conversion.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.