/ STM32 MACHASH - Copyright (C) 2014-2018 Clive Turvey (sourcer32@gmail.com)
// All Rights Reserved
#include <windows.h>
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char uint8_t;
typedef unsigned long uint32_t;
uint32_t Rev32(uint32_t x)
{
uint32_t y;
int i;
y = 0;
for(i=0; i<32; i++)
if (x & (1 << i))
y |= 1 << (31 - i);
return(y);
}
uint32_t MacHash(const uint8_t *Mac) // sourcer32@gmail.com
{
int i, j;
uint32_t Crc;
Crc = 0xFFFFFFFF;
for(j=0; j<6; j++)
{
Crc = Crc ^ (uint32_t)Mac[j];
for(i=0; i<8; i++)
if (Crc & 1)
Crc = (Crc >> 1) ^ 0xEDB88320; // Reversed 0x04C11DB7
else
Crc = (Crc >> 1);
}
return(Rev32(~Crc) >> 26); // Get High order 6-bit in reversed/inverted CRC
}
uint32_t MacHashFast(const uint8_t *Mac) // sourcer32@gmail.com
{
static const uint32_t Rev6Tbl[] = {
0x00,0x20,0x10,0x30,0x08,0x28,0x18,0x38,
0x04,0x24,0x14,0x34,0x0C,0x2C,0x1C,0x3C,
0x02,0x22,0x12,0x32,0x0A,0x2A,0x1A,0x3A,
0x06,0x26,0x16,0x36,0x0E,0x2E,0x1E,0x3E,
0x01,0x21,0x11,0x31,0x09,0x29,0x19,0x39,
0x05,0x25,0x15,0x35,0x0D,0x2D,0x1D,0x3D,
0x03,0x23,0x13,0x33,0x0B,0x2B,0x1B,0x3B,
0x07,0x27,0x17,0x37,0x0F,0x2F,0x1F,0x3F };
static const uint32_t Crc32Tbl[] = {
0x4DBDF21C, 0x500AE278, 0x76D3D2D4, 0x6B64C2B0,
0x3B61B38C, 0x26D6A3E8, 0x000F9344, 0x1DB88320,
0xA005713C, 0xBDB26158, 0x9B6B51F4, 0x86DC4190,
0xD6D930AC, 0xCB6E20C8, 0xEDB71064, 0xF0000000 };
int i;
uint32_t Crc;
Crc = 0;
for(i=0; i<6; i++)
{
Crc = Crc ^ (uint32_t)Mac[i];
Crc = (Crc >> 4) ^ Crc32Tbl[Crc & 0x0F]; /* lower nibble */
Crc = (Crc >> 4) ^ Crc32Tbl[Crc & 0x0F]; /* upper nibble */
}
return(Rev6Tbl[Crc & 0x3F]);
}
int main(int argc, char **argv)
{
static const uint8_t Test1[] = { 0x1F, 0x52, 0x41, 0x9C, 0xB6, 0xAF }; // 0x2C
static const uint8_t Test2[] = { 0xA0, 0x0A, 0x98, 0x00, 0x00, 0x45 }; // 0x07
static const uint8_t Test3[] = { 0x01, 0x00, 0x5e, 0x00, 0x00, 0x21 }; // 0x24
printf("MacHash %02X\n", MacHash(Test1));
printf("MacHash %02X\n", MacHash(Test2));
printf("MacHash %02X\n", MacHash(Test3));
printf("MacHashFast %02X\n", MacHashFast(Test1));
printf("MacHashFast %02X\n", MacHashFast(Test2));
printf("MacHashFast %02X\n", MacHashFast(Test3));
return(1);
}