Skip to content

Instantly share code, notes, and snippets.

@GrabYourPitchforks
Last active October 11, 2017 10:58
Show Gist options
  • Save GrabYourPitchforks/a309463508a31aaba093241f145d09ab to your computer and use it in GitHub Desktop.
Save GrabYourPitchforks/a309463508a31aaba093241f145d09ab to your computer and use it in GitHub Desktop.
// Input: a 32-bit integer of the form [ 00wwwwww 00xxxxxx 00yyyyyy 00zzzzzz ]
// Output: a 32-bit integer where each input byte is mapped to its corresponding BASE64 ASCII byte
private static uint ByteToBase64(uint b)
{
b += 0x41414141U; // 'A'
return b
+ (0x06U * (((b + 0x25252525U) & 0x80808080U) >> 7))
- (0x4BU * (((b + 0x0B0B0B0BU) & 0x80808080U) >> 7))
- (0x0FU * (((b + 0x01010101U) & 0x80808080U) >> 7))
+ (0x03U * ((b & 0x80808080U) >> 7));
}
// 64-bit version of above method
private static ulong ByteToBase64(ulong b)
{
b += 0x4141414141414141UL; // 'A'
return b
+ (0x06U * (((b + 0x2525252525252525UL) & 0x8080808080808080UL) >> 7))
- (0x4BU * (((b + 0x0B0B0B0B0B0B0B0BUL) & 0x8080808080808080UL) >> 7))
- (0x0FU * (((b + 0x0101010101010101UL) & 0x8080808080808080UL) >> 7))
+ (0x03U * ((b & 0x8080808080808080UL) >> 7));
}
// SIMD version of above method
// With hilariously large x86 generation
private static Vector<byte> ByteToBase64(Vector<byte> b)
{
b += new Vector<byte>(0x41); // 'A'
return b
+ (new Vector<byte>(0x06) & (Vector.GreaterThanOrEqual(b, new Vector<byte>(0x80 - 0x25))))
- (new Vector<byte>(0x4B) & (Vector.GreaterThanOrEqual(b, new Vector<byte>(0x80 - 0x0B))))
- (new Vector<byte>(0x0F) & (Vector.GreaterThanOrEqual(b, new Vector<byte>(0x80 - 0x01))))
+ (new Vector<byte>(0x03) & (Vector.GreaterThanOrEqual(b, new Vector<byte>(0x80 - 0x00))));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment