Byte range splitting


Series Overview

This article is part of the series. Below are links to all posts in the series:
  1. Byte Variables & Byte Arrays
  2. Byte Representations
  3. Base64 Encoding
  4. Byte Range Splitting

What's inside this article ⌄
  • Byte range midpoint calculation
  • Hex to decimal conversion python
  • Byte range splitting algorithm
  • Inclusive range boundaries programming

Suppose you have a byte range from 00 00 to ff ff. How you can split it into two parts?

Remember that every byte can be represented as a number? Even if it embodies raw data. The trick here is to temporarily use a decimal representation.

Our boundaries:

value1_hex = '0000'
value2_hex = 'ffff'

Let’s convert them to decimals:

value1_decimal = int(value1_hex, 16)
value2_decimal = int(value2_hex, 16)

Then, find a midpoint:

midpoint_decimal = (Decimal(value1_decimal) + Decimal(value2_decimal)) / 2

Then, convert back to hex:

midpoint_hex = hex(midpoint_decimal)
midpoint_hex = midpoint_hex[2:] # 0x8000 -> 8000

Here we go! midpoint_hex is our pivot. Therefore, two parts are: 0000-8000 and 8000-ffff.

Notice that sometimes we can encounter real numbers when computing a midpoint instead of integers.

Therefore, we have to choose: should we round it up or down? It’s common to impose a property called “inclusive”.

If inclusive was initially set to true, then we should round it up. If it’s false, we should round it down:

midpoint_decimal = (Decimal(value1_decimal) + Decimal(value2_decimal)) / 2

if inclusive:

midpoint_decimal = math.ceil(midpoint_decimal)

otherwise:

midpoint_decimal = math.floor(midpoint_decimal)

This code user is the one who decides how to set the property inclusive. You can easily write identical code in Java.