C# 3 byte Ints


I am working on a project where I need to deal at the byte level with integers. Since saving space is a primary consideration, I only need very small (and variable length ints).

Is there a way that I can turn the int '4096' into 3 bytes? or '1053' into a 2 bytes?

Obviously I cna do it manually = (byte[0] * 256) + (byte[1]), but i was wondering if there is an easier option to convert the int into x bytes and back again?

Best Solution

Can you? Sure. Will it save any space? Maybe, depending on how much work you want to do. You have to understand that the processor is 32-bit, meaning it has 4 byte registers, so that's how it's going to want to store and access things. To force a 3-byte "int" you'll have to keep it in a byte array, and extract it from the array to an aligned address before use. That means that if you store it short, the compiler will either pad it out (and you'll lose any efficiency you think you've created) or it will be a lot slower to read and write.

If this is a desktop app, how exactly is saving space a primary consideration, especially when talking 1 byte per element? The perf penalty for element access may change you mind about how critical that one byte is.

I'd argue that if that 1 byte truly is important, that maybe, just maybe, you're using the wrong language anyway. The number of bytes you'd save my not installing and using the CLR in the first place is a lot of those bytes.

Side note: You'd also do a shift, not a multiplication (though the compiler would likely get there for you).

Related Question