Skip to main content
GameDev.net gamedev.net
🔒 Locked

Storing 2 numbers in a byte

Started by Essentric Mar 14, 2011 at 8:44 PM 5 replies 1.9k views
Original Post
Essentric
Essentric
Hi, I want to store 2 small numbers in a byte, these numbers will be between 0 and 12. Is there a macro like the LOBYTE and HIBYTE that I can use for this. maybe called LOBITS/HIBITS lol

I'm using code::blocks / gcc win32 app
Buklenios
Buklenios
I'd try something like this:




int lowBits = 9;
int hiBits = 12;

char Value = (lowBits & 0xf) | ((hiBits & 0xf) << 4);


With some casting maybe if the compiler is not happy about it
decrezero
decrezero
Check out the section on bit fields:
http://www.cs.cf.ac.uk/Dave/C/node13.html

Or, you can write a macro/function with the bitwise operators.

Personally, I wouldn't bother with either; unless it's for network compression or some other highly bandwidth limited purpose.
Essentric
Essentric
It's for saving bandwidth, thanks for the quick replies
TheTroll
TheTroll
If you are trying to save bandwidth and these values get passed a lot you might just go with a bit array instead of a byte. This allows you to send one number, two or more. Gives you he flexibility you might want in the future.

theTroll
RabblePants
RabblePants
You can try something like this:


union
{
unsigned char val;
struct
{
unsigned int hi: 4;
unsigned int lo: 4;
} parts;
};


Makes it a little easier and avoids bitshifting in favor slightly more readable code
Sik_the_hedgehog
Sik_the_hedgehog
If you want to save the values in a file or send them to another computer through a network or something, that isn't very safe though, since the compiler is free to choose how the bits get arranged. One compiler may put [font="Courier New"]hi[/font] in the upper bits and [font="Courier New"]lo[/font] in the lower bits, another compiler may do the exact opposite. Not a nice situation if you want portability across systems.

And then there's the deal of compilers just adding padding for the sake of performance (meaning not even alignment is guaranteed), although I don't think a compiler will add padding unless something would cross a byte/word/whatever boundary.
Don't pay much attention to "the hedgehog" in my nick, it's just because "Sik" was already taken =/ By the way, Sik is pronounced like seek, not like sick.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.