Add Common::HashCrc16 and Common::HashCrc7

This commit is contained in:
Pokechu22 2020-08-24 13:17:03 -07:00
parent 4f6cd4f535
commit d0d8661f9b
2 changed files with 60 additions and 0 deletions

View File

@ -446,4 +446,48 @@ u32 ComputeCRC32(std::string_view data)
{
return ComputeCRC32(reinterpret_cast<const u8*>(data.data()), data.size());
}
u8 HashCrc7(const u8* ptr, size_t length)
{
// Used for SD cards
constexpr u8 CRC_POLYNOMIAL = 0x09;
u8 result = 0;
for (size_t i = 0; i < length; i++)
{
// TODO: Cache in a table
result ^= ptr[i];
for (auto bit = 0; bit < 8; bit++)
{
if (result & 0x80)
result = (result << 1) ^ (CRC_POLYNOMIAL << 1);
else
result = result << 1;
}
}
return result >> 1;
}
u16 HashCrc16(const u8* ptr, size_t length)
{
// Specifically CRC-16-CCITT, used for SD cards
constexpr u16 CRC_POLYNOMIAL = 0x1021;
u16 result = 0;
for (size_t i = 0; i < length; i++)
{
// TODO: Cache in a table
result ^= (ptr[i] << 8);
for (auto bit = 0; bit < 8; bit++)
{
if (result & 0x8000)
result = (result << 1) ^ CRC_POLYNOMIAL;
else
result = result << 1;
}
}
return result;
}
} // namespace Common

View File

@ -3,6 +3,7 @@
#pragma once
#include <array>
#include <cstddef>
#include <string_view>
@ -21,4 +22,19 @@ u32 StartCRC32();
u32 UpdateCRC32(u32 crc, const u8* data, size_t len);
u32 ComputeCRC32(const u8* data, size_t len);
u32 ComputeCRC32(std::string_view data);
// For SD card emulation
u8 HashCrc7(const u8* ptr, size_t length);
u16 HashCrc16(const u8* ptr, size_t length);
template <size_t N>
u8 HashCrc7(const std::array<u8, N>& data)
{
return HashCrc7(data.data(), N);
}
template <size_t N>
u16 HashCrc16(const std::array<u8, N>& data)
{
return HashCrc16(data.data(), N);
}
} // namespace Common