can someone explain to me how to view binary?

Started by
2 comments, last by amemorex 22 years, 2 months ago
In my program there are a bunch of options that I want saveable to a text file, all just a bunch of true/false conditions.. I''d like to store the values of these in a simple binary..something or another..sorta how Gnutella/etc does when they convert your IP address sorta like this.. 67.112.45.36 -> (char)67 + (char)112 + (char)45 + (char)36 Thus giving you some 4-letter string that reduces the bytesize of your packet fairly well. Well I don''t know if this applies to what I''m trying to do, but lets say I have 8 values that can either be true or false..How do I store these 8 values as individual bits making up a byte..like 11010010 And then turn that into hex, and then into ASCII, creating a simple character. Even further..how would I go about breaking down the character into it''s bits to retrieve the values?
Advertisement
look up bit shifting, that should help with you problem
Read up on binary operators (shift left, shift right, and, or, xor, etc). It''s been awhile since I''ve had to bit twiddle, so there may be a more efficient way to do this, but here goes.

Make a bitmask for each of the bits you want to set:

BITMASK_4 = 0x4; // 0000 1000

To set that bit:

storage_integer = BITMASK_4 (or) storage_integer;

To unset that bit:

storage_integer = ((not) BITMASK_4) (and) storage_integer;

Replace (not), (and), (or) with the appropriate bitwise operators for your language.
void SetBit(int bit)
{
int bytepos = bit/32;
int bitmask = 1<<(bit%32);
m_dwStorage[bytepos] |= bitmask;
}
(Here too, assembly would be useful because there's an integer divide returns the friggin' reminder as well the divisor!)

void ClrBit(int bitpos)
{
int bytepos = bit/32;
int bitmask = 1<<(bit%32);
m_dwStorage[bytepos] &= ~bitmask;
}

//remember, 0 is false, else it is true
BOOL GetBit(int bitpos)
{
int bytepos = bit/32;
int bitmask = 1<<(bit%32);
return m_dwStorage[bytepos] & ~bitmask;
}
... I think that works (off the top of my head, check it if you use it)


Now, to convert an ipaddress to a binary address you use gethostbyname, it takes an ansi string, returns a hostent (union of stuff that makes up an internet address, the ip + the port). It'll work for 67.11.45.36 and for www.yahoo.com

Edited by - Magmai Kai Holmlor on February 20, 2002 12:19:02 AM
- The trade-off between price and quality does not exist in Japan. Rather, the idea that high quality brings on cost reduction is widely accepted.-- Tajima & Matsubara

This topic is closed to new replies.

Advertisement