7.9 Converting Integers into Binary Strings for Use with RSA

7.9.1 Problem

You have a number as a result of an RSA operation that you'd like to turn into a binary string of a fixed length.

7.9.2 Solution

Use the inverse of the previous recipe, padding the start of the string with zero-bits, if necessary, to reach the desired output length. If the number is too big, return an error.

7.9.3 Discussion

In practice, you should be using a binary representation of very large integers that stores a value as an array of values of type unsigned int or type char. If you're using a little-endian machine and word-sized storage, each word will need to be byte- swapped before the value can be treated as a binary string.

Byte swapping can be done with the htonl( ) macro, which can be imported by including arpa/inet.h on Unix or winsock.h on Windows.