0% found this document useful (0 votes)
35 views5 pages

Binary Literals

Uploaded by

Fernando Lagos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views5 pages

Binary Literals

Uploaded by

Fernando Lagos
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Binary literals in C@Everything2.

com

Near Matches

Ignore Exact

Binary literals in C
Login:
(thing) by call (11.6 hr) (print) ? 1 C! Fri Aug 30 2002 at 12:59:42
Password

The C programming language is an excellent one for all us bit twiddlers, blessed as it is with the full remember me Login
password reminder
complement of bitwise operations, and no performance overheads that aren't visible in the language (in
Create a New User
other words, integral variables are usually in registers). Random Node
Create a Node

Also of benefit to us, it has a variety of number bases in which we can write literal values: decimal (by just [ * ] Read 'Em or Weep
writing, eg. 9999), hexadecimal (by prefixing with '0x', eg 0xffff), and even octal (by prefixing with '0', eg. Getting Started
07777). Quick Start
Everything FAQ
Everything University
Notable by its omission, however, and quite frustrating to us low-level types, is the presence of any way of Voting/Experience System
representing binary literal values. This perplexed and annoyed me for many a year, until recently when I E2 Mentoring Sign-Up
realised that there's a plethora of simple ways to construct an integer from something that looks very much
like (but isn't really) a binary value.

Strings would be the obvious candidate; we all know it's possible to construct a binary value from a string. Look at this mess the Death
Borg made!
However, this almost always has to be done at run time; iteration over a variable length string can't be made
Pushkin and Gogol
constant, and few compilers are smart enough to realise that a const function with constant parameters
These Are Days
can be entirely computed at compile time.
Underdark
Cissoid
A better candidate for this is C's already existing numerical literals. Digits in every number base greater than OGR
binary can take on the values 0 and 1, as well as other values. We can exploit this by converting a literal Ono-Sendai
(say, octal or decimal) which happens to look a lot like a binary number, (with a wildly differing value) into netism
the value that the corresponding binary number would have.
Lardoon
The Wild Geese
Say, for example, we wanted to represent the binary constant 1101bin (Eight and four and one; or thirteen)
Stroop test
in our program source code. We can express this as a constant function of the integer 1101dec (one
Kenneth Oppel
thousand, one hundred and one). The value of the integer we want to represent (thirteen) is simply (1 if the Rafael van der Vaart
1's digit is 1) + (2 if the 10s digit is 1) + (4 if the 100s digit is 1) + (8 if the 1000s digit is 1). Since this is all
simple arithmetic on constant integers, the literal can be completely evaluated by the compiler at compile
time. Oatie
Staffordshire Oatcakes (place)
Here's a C macro that converts a binary-esque decimal value into an integer with the value that the Darkmaelstrom
corresponding binary would have had: June 8th, 1944 (idea)
etouffee
Erasable (idea)
/* To extract each bit value; divide by appropriate power of 10, Alienof2000
if result has a '1' set in that position, corresponds to
ampulex compressa (thing)
a 1 in that position in the literal => set bit.
iceowl
This allows us to write the binary value 1101 (thirteen) as How to fly (idea)
BIN(1101), a constant function of the decimal value 1101 DejaMorgana
(one thousand one hundred and one). oats (thing)
*/ Cinderella
#define BIN_BIT(value, bit, dec) ((((unsigned) value/dec)&1 == 1)? (1<<bit) : 0) Happy Birthday, Dad (thing)
Glowing Fish
/* Put 10 bits together to form a 10 bit constant. */
The Internet as Killer App (idea)
#define BIN(value) \
Glowing Fish
( BIN_BIT(value, 0, 1) | \
BIN_BIT(value, 1, 10) | \ savings (idea)

BIN_BIT(value, 2, 100) | \ FredPenner


BIN_BIT(value, 3, 1000) | \ 500 (idea)
BIN_BIT(value, 4, 10000) | \ Sol Invictus
BIN_BIT(value, 5, 100000) | \ Roy Orbison in Clingfilm (idea)
BIN_BIT(value, 6, 1000000) | \ perplexion
BIN_BIT(value, 7, 10000000) | \
Cowon iAudio U2 (thing)
BIN_BIT(value, 8, 100000000) | \
Timeshredder
BIN_BIT(value, 9, 1000000000) )
The Tempest (thing)

http://everything2.com/index.pl?node_id=1354309 (1 of 3)04/02/2006 17:38:42


Binary literals in [email protected]

/* GCC-specific: use a 64-bit long long literal to produce a 20-bit artman2003


binary number. */ duck (thing)
#define BIN_BIT64(value, bit, dec) ((((unsigned long long) \ Ivix
value/dec)&1 == 1)? (1<<bit) : 0) King's Quest VI - Heir
(thing)
Today, Gone Tomorrow
#define BIN20(value) \
( BIN_BIT64(value, 0, 1ull) | \
BIN_BIT64(value, 1, 10ull) | \ [ * ] Maintenance
BIN_BIT64(value, 2, 100ull) | \ Node Title Edit
BIN_BIT64(value, 3, 1000ull) | \
Broken Writeups
BIN_BIT64(value, 4, 10000ull) | \
BIN_BIT64(value, 5, 100000ull) | \ Writeup Deletion Request
BIN_BIT64(value, 6, 1000000ull) | \ Nodeshell Deletion Request
BIN_BIT64(value, 7, 10000000ull) | \ Node Heaven
BIN_BIT64(value, 8, 100000000ull) | \ E2 Bugs
BIN_BIT64(value, 9, 1000000000ull) | \ Suggestions for E2
BIN_BIT64(value, 10, 10000000000ull) | \
BIN_BIT64(value, 11, 100000000000ull) | \ [ * ] Noding Information
BIN_BIT64(value, 12, 1000000000000ull) | \ E2 HTML Tags
BIN_BIT64(value, 13, 10000000000000ull) | \
HTML symbol reference
BIN_BIT64(value, 14, 100000000000000ull) | \
BIN_BIT64(value, 15, 1000000000000000ull) | \ Using Unicode on E2
BIN_BIT64(value, 16, 10000000000000000ull) | \ Reference Desk
BIN_BIT64(value, 17, 100000000000000000ull) | \
BIN_BIT64(value, 18, 1000000000000000000ull) | \ [ * ] Noding Utilities
BIN_BIT64(value, 19, 10000000000000000000ull) ) E2 Scratch Pad
Scratch Pad Viewer
Source Code Formatter
There are some obvious caveats with the above code: Text Formatter

[ * ] Lists
● When writing binary constants, it's tempting to write preceding zeros at the beginning of the number
100 Newest Writeups
to pad it to a fixed number of bits. However, doing this here (eg. BIN(01001011)) would turn the
decimal literal into an octal literal, giving entirely the wrong value. Cool Archive (C! writeups)
● Since decimal needs more than a single bit to represent each digit, the number of digits in literal Page of Cool (Editor Picks)
values is smaller; only 10 bits can be represented by a 32-bit number, or 20 by a 64-bit number. A Year Ago Today
Everything Finger
Everything User Search
That being said, however, the above method can be generalised to any number base by using appropriate
Old News
constants, so long as the base is smaller than the largest base that can be represented (base 16) in C's
literal constants. Everything's Most Wanted

[ * ] Miscellaneous
Voting/Experience System
Message Inbox
(idea) by Stavr0 (2.2 wk) (print) ? Fri Aug 30 2002 at 18:00:40 Java Chatterbox
chatterlight
Gab Central
When writing binary constants, it's tempting to write preceding zeros at the beginning of the
number to pad it to a fixed number of bits. However, doing this here (eg. BIN(01001011)) Everything User Poll
would turn the decimal literal into an octal literal, giving entirely the wrong value. Everything Quote Server

The octal literals, far from being a problem, could be used just the same: Donation Box
E2 Merchandise
#define BIN_BITO(value, shift, mask) (((unsigned)value&mask)>>shift)

/* Put 10 bits together to form a 10 bit constant. */ You must log in first.
#define BINO(value) \
( BIN_BITO(0##value, 0, 01) | \
BIN_BITO(0##value, 2, 010) | \
BIN_BITO(0##value, 4, 0100) | \
BIN_BITO(0##value, 6, 01000) | \
BIN_BITO(0##value, 8, 010000) | \
BIN_BITO(0##value, 10, 0100000) | \
BIN_BITO(0##value, 12, 01000000) | \
BIN_BITO(0##value, 14, 010000000) | \
BIN_BITO(0##value, 16, 0100000000) | \
BIN_BITO(0##value, 18, 01000000000) )

If you need bigger bit constants, this simple macro will do:

http://everything2.com/index.pl?node_id=1354309 (2 of 3)04/02/2006 17:38:42


Binary literals in [email protected]

#define BIN32(b24,b16,b8,b0) \
((BINO(b24)&0xff&LT;&LT;24)| \
(BINO(b16)&0xff&LT;&LT;16)| \
(BINO(b8)&0xff&LT;&LT;8) | \
(BINO(b0)&0xff) )

(idea) by tardibear (1 mon) (print) ? 1 C! Wed Sep 04 2002 at 9:39:15

In this case the template meta-programming solution is rather more concise :-

template<int N>
struct B {
enum {Ndiv10 = N / 10};
enum {Nrem10 = N - 10*Ndiv10};
enum {R = Nrem10 + 2*B<Ndiv10>::R};
};

template<>
struct B<0> {
enum {R = 0};
};

...

const int mask = B<100110>::R;

printable version

chaos

template meta-programming In C bit twiddling variadic macros in C

Useful Number Theory Learn C, you


C99 hexadecimal
functions in C hippies

Mick strlen metaprogramming octal

Template why Wicked machine language

hex source code

Y'know, if you login, you can write something here. You can also Create a New User if you don't already
have an account.

Everything 2 is brought to you by the letter C and The Everything Development Company

give money give me something for my money


Please report server problems to e2webmaster at everything2.com

http://everything2.com/index.pl?node_id=1354309 (3 of 3)04/02/2006 17:38:42


C++: computing Fibonacci numbers at compile [email protected]

Near Matches

Ignore Exact

C++: computing Fibonacci numbers at compile time


Login:
(thing) by ariels (4.4 hr) (print) ? 1 C! Thu Dec 28 2000 at 7:58:32
Password

Every programming language enthusiast has written programs to compute the Fibonacci numbers in remember me Login
password reminder
every programming language. That's easy, and gets boring pretty soon.
Create a New User
Random Node
But C++ enthusiasts can go one better. That's because C++ conforms to the slogan "buy one C++ Create a Node

compiler, get another interpreted language free!". So C++ can compute Fibonacci numbers at [ * ] Read 'Em or Weep
compile time!!!1! Getting Started
Quick Start
Everything FAQ
Here's how to do it. Note that the syntax of the compile time language (aka C++ templates) is nothing Everything University
like what you know of C++. This is absolutely normal in C++; every C++ program looks almost Voting/Experience System
exactly nothing like any other C++ program. E2 Mentoring Sign-Up

template<int N> struct fib {


static const int result = fib<N-1>::result + fib<N-2>::result;
}; Look at this mess the Death
Borg made!
struct fib<0> { Pushkin and Gogol
static const int result = 0; These Are Days
}; Underdark
Cissoid
struct fib<1> { OGR
static const int result = 1; Ono-Sendai
};
netism
#include <iostream> Lardoon
int main(int ac, char *av[]) The Wild Geese
{ Stroop test
std::cout << "Fib(10) = " << fib<10>::result << std::endl; Kenneth Oppel
return 0; Rafael van der Vaart
}
Oatie
C++ advocates will have no problems explaining why this program has linear compilation time in N, Staffordshire Oatcakes (place)
rather than the expected exponential compilation time due to the algorithm used. Interestingly, a Darkmaelstrom
vastly more complicated struct with logarithmic compilation time (see Compute Fibonacci numbers June 8th, 1944 (idea)
FAST! for the algorithm, albeit in readable pseudocode rather than template meta-programming etouffee
nonsense like the above) takes much longer to compile (presumably due to increased complexity). Erasable (idea)
Alienof2000
Warning ampulex compressa (thing)
iceowl
You may need to increase your compiler's template depth to compile this code! The gcc incantation is - How to fly (idea)
ftemplate-depth-33 or somesuch. DejaMorgana
oats (thing)
Cinderella
Happy Birthday, Dad (thing)
Glowing Fish
printable version The Internet as Killer App (idea)
Glowing Fish
chaos savings (idea)
FredPenner
500 (idea)
Sol Invictus
Roy Orbison in Clingfilm (idea)
perplexion

http://everything2.com/index.pl?node_id=891199 (1 of 2)04/02/2006 17:40:12


C++: computing Fibonacci numbers at compile [email protected]

Cowon iAudio U2 (thing)

Compute Timeshredder
The C++ Programming The Tempest (thing)
Fibonacci Getting free pizza Fibonacci number
Language Freakshow artman2003
numbers FAST!
duck (thing)
Ivix
If the field of AI
King's Quest VI - Heir
had tried building (thing)
Today, Gone Tomorrow
C++: how the parser footballers rather
blitz++ Why C++ sucks and the lexer fight than chess
over templates players, how might [ * ] Maintenance
it be different Node Title Edit
today? Broken Writeups
Writeup Deletion Request
When time travel Nodeshell Deletion Request
in science fiction template meta- Node Heaven
compile time Quadratic Equation E2 Bugs
just doesn't make programming
any sense Suggestions for E2

[ * ] Noding Information
C++: Checking units at E2 HTML Tags
class template C++ multitype Euclid's algorithm
compile time HTML symbol reference
Using Unicode on E2
Why buy the cow Reference Desk
C++ ISO 9000 incantation when you can get
the milk for free? [ * ] Noding Utilities
E2 Scratch Pad
C++: function templates Scratch Pad Viewer
C++ templates interpreted language phi Source Code Formatter
and information hiding
Text Formatter

[ * ] Lists
Y'know, if you login, you can write something here. You can also Create a New User if you don't 100 Newest Writeups
already have an account. Cool Archive (C! writeups)
Page of Cool (Editor Picks)
A Year Ago Today
Everything Finger
Everything User Search
Old News
Everything's Most Wanted

[ * ] Miscellaneous
Voting/Experience System
Message Inbox
Java Chatterbox
chatterlight
Gab Central
Everything User Poll
Everything Quote Server

Donation Box
E2 Merchandise

You must log in first.

Everything 2 is brought to you by the letter C and The Everything Development Company

give it all away or go shopping


Please report server problems to e2webmaster at everything2.com

http://everything2.com/index.pl?node_id=891199 (2 of 2)04/02/2006 17:40:12

You might also like