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

binary numbers

Started by A_B Jun 9, 2009 at 4:05 AM 14 replies 2k views
Original Post
A_B
A_B
Hi, I need to represent a strip of data of which each element can be either true or false, and i need access to each element to edit it. The logical way to represent this seemed to me to be binary numbers. So my question is, if I define a binary number like so: #define BN 0000 0101 How can I, for example, check if the 3rd number is a zero and if it is change it to a 1? I would consider converting the binary to a string but would it be better then to just use a string in the first place (also considering speed of the program)? Thanks A_B
DevFred
DevFred
Unfortunately, C++ provides no binary literals. But if the numbers fit into 10 bits, you can use some template metaprogramming:

#include <iostream>template<unsigned n>struct bit;template<>struct bit<0>{    enum { value = 0 };};template<>struct bit<1>{    enum { value = 1 };};template<unsigned n>struct binary{    enum { value = bit<n%10>::value + 2*binary<n/10>::value };};template<>struct binary<0>{    enum { value = 0 };};int main(){    std::cout << binary<  0>::value << std::endl;    std::cout << binary<  1>::value << std::endl;    std::cout << binary< 10>::value << std::endl;    std::cout << binary< 11>::value << std::endl;    std::cout << binary<100>::value << std::endl;    std::cout << binary<101>::value << std::endl;    std::cout << binary<110>::value << std::endl;    std::cout << binary<111>::value << std::endl;}


Quote:
Original post by A_B
How can I, for example, check if the 3rd number is a zero and if it is change it to a 1?

If it is 0, you want to set it to 1, and if it is 1, you want to leave it at 1? Then there's no need for the if -- just set it to 1.
int number = binary<1011>::value;    number|= binary< 100>::value;
Captain P
Captain P
Quote:
How can I, for example, check if the 3rd number is a zero and if it is change it to a 1?

value |= 4; // 4 == 100b

Quote:
I would consider converting the binary to a string but would it be better then to just use a string in the first place (also considering speed of the program)?

std::vector is specialized for this purpose. It stores the booleans as bits rather than bools, to save some memory. It therefore behaves a little different than a normal vector, but that's likely not a problem for your purposes.
A_B
A_B
Thanks all,

It seems quit strange to me that a programming language does not allow working with binary numbers, since that is what the computer actually does. You replies helped me a lot, thanks.

A_B
XTAL256
XTAL256
Quote:
Original post by A_B
It seems quit strange to me that a programming language does not allow working with binary numbers, since that is what the computer actually does.

Actually it doesn't. Well, not in the way you want. A 32-bit computer will manipulate one 32-bit number at a time but cannot access individual bits. Some (8051 i believe) have bit-wise access to parts of memory but that is not really needed nowadays. To get individual bits in C/C++ use bit masking like what Captain P demonstrated.
[Window Detective] - Windows UI spy utility for programmers
Erik Rufelt
Erik Rufelt
Quote:
Original post by A_B
It seems quit strange to me that a programming language does not allow working with binary numbers, since that is what the computer actually does. You replies helped me a lot, thanks.


It does allow that, by using something like the following, to check if the third bit from the right is 0 and if so change it to a 1:
if((BN & (1 << 3)) == 0) BN |= (1 << 3);


The computer doesn't really work with bits in that way though, almost everything is done on 32-bit numbers at a time in a 32-bit program. The actual instructions in the CPU work on 32 bits at a time, and it's often at least as fast to change the whole 32 bit number rather than just one of it's bits, unless you have a very specific situation where using less memory is beneficial.
DevFred
DevFred
If you don't need the values at compile time, you can also parse strings at runtime:
unsigned binary(char const* s){    int x = 0, c;    while (c = *s++) x += x + (c - '0');    return x;}int main(){    std::cout << binary("00010010") << std::endl;}
A_B
A_B
I love you, Weetbix :p
that's exactly what I needed.
phresnel
phresnel
Quote:
Original post by A_B
Thanks all,

It seems quit strange to me that a programming language does not allow working with binary numbers, since that is what the computer actually does. You replies helped me a lot, thanks.

A_B


Though consider that actual binary representations are generally not relevant to a programming language itself; a compiler for C++ could as well be written for a machine that has more than 2 states per transistor (the reason why binary states have been chosen is that they can be stored in the most stable way, the more states you add per transistor, the more error prone storage is thanks to things like fluctuations in electricity; with binaries, there is a maximum electricity below which the state of the transistor is interpreted as false, or zero, then there's a dead zone for which digits are interpreted as corrupt, and beyond some minimum electricity it is interpreted as true; all that is of course very simplified).
smurfkiller
smurfkiller
Also depends how you gonna use your binary numbers. For performance i would use a 8-32 bits type and make some functions/macros to manipulate single bits. If you do alot of computations with your binary numbers and just want to manipulate single bits you dont wanna use a 'bitset'. Convert too and from binary string representation is as trivial as for a 'bitset'.

But you right about one thing that it would not be a great effort to have bin representation of numbers. Some C compilers, mostly for microcontroller processors actualy have a binary number representation like "int a = 00100101b;"
Crush your enemies, see them driven before you, and hear the lamentations of their women!
phresnel
phresnel
Quote:
Original post by smurfkiller
8-32 bits type

Surely those depend on the architecture (which is nowadays and never was Intel x86): Fastest minimum width integer types. Also.

Quote:
and make some functions/macros/templates, but avoid macros in C++

Rephrased for the C++ case ;)

Quote:
Some C compilers, mostly for microcontroller processors actualy have a binary number representation like "int a = 00100101b;"

Indeed, but then that's not C++ standards conforming and afaik also not C standards conforming. But then, such low-level programming of course is allowed to fully utilize compiler extensions. Sidenote: The OS kernel Linux (low level) and afair BSD depend on tons of compiler extensions. Can't say anything about Windows, but I bet they do it, too.
Sik_the_hedgehog
Sik_the_hedgehog
In any case you can always just use hexadecimal literals =P One hexadecimal digit is the equivalent to four binary digits. You enter them like this in the case of C and C++: 0x1234 (that's like 0001 0010 0011 0100 in binary).
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.
phresnel
phresnel
Quote:
Original post by Sik_the_hedgehog
In any case you can always just use hexadecimal literals =P One hexadecimal digit is the equivalent to four binary digits. You enter them like this in the case of C and C++: 0x1234 (that's like 0001 0010 0011 0100 in binary).


Alternatively, you can also write octal numbers, where each digit represent three bits, yay. Format is basically 0[0-9]*, with usual integer postfixes allowed.
alvaro
alvaro
Quote:
Original post by phresnel
Alternatively, you can also write octal numbers, where each digit represent three bits, yay. Format is basically 0[0-9]*, with usual integer postfixes allowed.

No. The format is 0[0-7]*. You'll get a compilation error if you use an 8 or a 9 in an octal expression.
phresnel
phresnel
Quote:
Original post by alvaro
Quote:
Original post by phresnel
Alternatively, you can also write octal numbers, where each digit represent three bits, yay. Format is basically 0[0-9]*, with usual integer postfixes allowed.

No. The format is 0[0-7]*. You'll get a compilation error if you use an 8 or a 9 in an octal expression.


D'Oh, that failure came from my habit of writing [0-9] in regexen (read: I am very used to write that special sequence [0-9]), instead of using proper character groups and special signs.

Here's an interesting sidenote:

        const float x = 0xFe9f;        const float y = 07e9f;        const double p = 0xFe9;        const double q = 07e9;        const long double a = 0xFe9L;        const long double b = 07e9L;


See also this. Note that hexadecimal-floating-point-constants are C99, and if I looked right, C++0x won't have them (see page 25: "Floating Literals" in C++0x draft September 2008), though GCC supports them as an extension to C++.

Topic Locked

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

Sign in to reply to this topic.