stuff-from-scratch/src/core/ByteUtils.h

82 lines
2 KiB
C
Raw Normal View History

2020-05-03 06:56:27 +00:00
#pragma once
#include <cstring>
class ByteUtils
{
public:
2021-03-29 20:31:24 +00:00
using Word = int;
using DWord = int;
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static int GetWordFirstBit(const Word word)
{
return word & ByteUtils::WORD_FIRST_BIT;
};
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static int GetWordLastByte(const Word word)
{
return word & ByteUtils::WORD_LAST_BYTE;
}
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static void ReverseBuffer(char* buffer, char* reverse, unsigned size)
{
for(unsigned idx=0; idx<size; idx++)
{
reverse[idx] = buffer[size - 1 -idx];
}
}
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static int ToInt(char* buffer, const unsigned size, bool reverse = true)
{
int result;
if(reverse)
{
std::string reversed;
ReverseBuffer(buffer, reversed.data(), size);
std::memcpy(&result, reversed.data(), sizeof(int));
}
else
{
std::memcpy(&result, buffer, sizeof(int));
}
return result;
}
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static Word ToWord(char* buffer, bool reverse = true)
{
return ToInt(buffer, BYTES_PER_WORD, reverse);
}
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static DWord ToDWord(char* buffer, bool reverse = true)
{
return ToInt(buffer, BYTES_PER_DWORD, reverse);
}
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static bool Compare(char* buffer, const char* tag, unsigned size)
{
for(unsigned idx=0; idx<size; idx++)
{
if(tag[idx] != buffer[idx])
{
return false;
}
}
return true;
}
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static bool CompareDWords(char* buffer, const char* tag)
{
return Compare(buffer, tag, BYTES_PER_DWORD);
}
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static bool CompareWords(char* buffer, const char* tag)
{
return Compare(buffer, tag, BYTES_PER_WORD);
}
2020-05-03 06:56:27 +00:00
2021-03-29 20:31:24 +00:00
static const int BYTES_PER_WORD = 2;
static const int BYTES_PER_DWORD = 4;
static const int BYTE_FIRST_BIT = 0x40; // 1000 0000
static const int WORD_FIRST_BIT = 0x8000; // 1000 0000 - 0000 0000
static const int WORD_LAST_BYTE = 0x00FF; // 0000 0000 - 1111 1111
2020-05-03 06:56:27 +00:00
};