Convert a Python Int into a Big-Endian String of Bytes

Converting big endian bytes into integer?

Disregarding any other problem. There are many ways to do this, essentially what you are asking is how to take a byte array that represent a 16 bit value (short,Int16) and assign it to an int

Given

public static int IntFromBigEndianBytes(byte[] data) 
=> (data[0] << 8) | data[1];

public static int IntFromBigEndianBytes2(byte[] data)
=> BitConverter.ToInt16(data.Reverse().ToArray());

Usage

var someArray = new byte[]{0x10, 0x24};

Console.WriteLine(IntFromBigEndianBytes(someArray));
Console.WriteLine(IntFromBigEndianBytes2(someArray));

Output

4132
4132

Full Demo Here

Note you should also be using BitConverter.IsLittleEndian == false to determine the endianness of your system with these methods, and reverse the logic on a big endian architecture

How to convert and Integer to an 64-bit byte representation in python

int.to_bytes

>>> value = 1
>>> value.to_bytes(8, 'big')
b'\x00\x00\x00\x00\x00\x00\x00\x01'

(Your sample output is 128 bits, so if you meant that, use 16.)

How to convert a string of bytes into an int?

You can also use the struct module to do this:

>>> struct.unpack("<L", "y\xcc\xa6\xbb")[0]
3148270713L


Related Topics



Leave a reply



Submit