Is there a way to make custom casts, like for a word of 15 bytes or for one of half a byte?
Assuming that char is 8 bits:
Code:
#include <iostream>
#include <iomanip>
using namespace std;
typedef unsigned char byte;
inline byte get_first(byte b) { return b >> 4; }
inline byte get_second(byte b) { return b & 0xf; }
inline void set_first(byte& b, byte d) { b |= d << 4; }
inline void set_second(byte& b, byte d) { b |= d & 0x0f; }
int main() {
// Declare two half-bytes
byte b = 0;
set_first(b, 0xa);
set_second(b, 0x5);
cout << "1st half-byte = 0x" << hex << static_cast<int>(get_first(b)) << '\n';
cout << "2nd half-byte = 0x" << hex << static_cast<int>(get_second(b)) << '\n';
}
Or something of the kind. Of course you can wrap this up in a class and together with operator overloading provide a cleaner interface. The 15 byte type will be more difficult and quite expensive in computing power. Are you sure you need such big numbers?
Another problem I have are the following casts.The first cast works. The 2nd gives the error "Cannot cast from 'int' to 'unsigned char'".
Code:
int value
unsigned char uchvalue = (unsigned char)value;
unsigned char uchvalue = reinterpret_cast<unsigned char>(value);
Use static_cast for such casts. You can also let it convert it implicitly, though most compilers will give a warning about possible loss of data.