Subject: It will look great with anything you put on.

From: Bra With No Hooks or Wires <[email-masked]>
Date: Fri, 15 Aug 2014 09:43:46 -0700

Ladies listen up....

Your bra doesn't have to be uncomfortable. Struggling with hooks and wires digging in your rib cage is no fun.

-

Celebrities are using this to look busty; not to mention the comfort is superb .

-

[Learn More]

On the question 'why do we need to use bit-fields', in Google I found that bit fields are used for flags. Now I am curious, is it the only way bit-fields are used practically? Do we need to use bit fields to save space?

Way of defining bit field from the book:

struct {
unsigned int is_keyword : 1;
unsigned int is_extern : 1;
unsigned int is_static : 1;
} flags;
Why do we use int? How much space is occupied? I am confused why we are using int, but not short or smith smaller than int. As I understand only 1 bit is occupied in memory, but not the whole unsigned int value. Is it correct?

c
share|improve this question
edited Jul 24 at 12:13

Mgetz
2,6171821
asked Jul 24 at 12:06

PutinHuylo
875
2
As about everything about bit-field is implementation defined, never? ouah Jul 24 at 13:17
add a comment
11 Answers
activeoldestvotes
up vote
8
down vote
accepted
Now I am curious, [are flags] the only way bit-fields are used practically?

No, flags are not the the only way bit-fields are used. They can also be used to store values larger than one bit, although flags are more common. For instance:

typedef enum {
NORTH = 0,
EAST = 1,
SOUTH = 2,
WEST = 3
} directionValues;

struct {
unsigned int alice_dir : 2;
unsigned int bob_dir : 2;
} directions;
Do we need to use bit fields to save space?

Bit fields do save space. They also allow an easier way to set values that aren't byte-aligned. Rather than bit-shifting and using bitwise operations, we can use the same syntax as setting fields in a struct. This improves readability. With a bitfield, you could write

directions.bob_dir = SOUTH;
However, doing it manually, you would need to write something like:

#define BOB_OFFSET 2
directions &= ~(3BOB_OFFSET); // clear Bob's bits
directions |= SOUTHBOB_OFFSET;
This improved readability is arguably more important than saving a few bytes here and there.

Why do we use int? How much space is occupied?

The space of an entire int is occupied. We use int because in many cases, it doesn't really matter. If, for a single value, you use 4 bytes instead of 1 or 2, your user probably won't notice. For some platforms, size does matter more, and you can use other data types which take up less space (char, short, uint8_t, etc).

As I understand only 1 bit is occupied in memory, but not the whole unsigned int value. Is it correct?

No, that is not correct. The entire unsigned int will exist, even if you're only using 8 of its bits.

share|improve this answer
edited Jul 25 at 11:09

answered Jul 24 at 13:17

Eric Finn
2,546625
add a comment

up vote
17
down vote
A quite good resource is Bit Fields in C.

The basic reason is to reduce the size used. For example if your write:

struct {
unsigned int is_keyword;
unsigned int is_extern;
unsigned int is_static;
} flags;
You will use at least 3 * sizeof(unsigned int) or 12 bytes to represent 3 little flags, that should only need 3 bits.

So if you write:

struct {
unsigned int is_keyword : 1;
unsigned int is_extern : 1;
unsigned int is_static : 1;
} flags;
This uses up the same space as one unsigned int, so 4 bytes. You can throw 32 one bit fields into the struct before it needs more space.

This is sort of equivalent to the classical home brew bit field:

#define IS_KEYWORD 0x01
#define IS_EXTERN 0x02
#define IS_STATIC 0x04
unsigned int flags;
But the bit field syntax is cleaner, compare:

if (flags.is_keyword)
against:

if (flags & IS_KEYWORD)
and obviously less error prone.

share|improve this answer
edited Jul 24 at 12:21

Niall
3,048835
answered Jul 24 at 12:18

rioki
2,3021030
1
Nice answer When talking about bit fields and their size in memory one should keep in mind that c++ compilers will allocate bit-fields in memory as follows: several consecutive bit-field members of the same type will be allocated sequentially. As soon as a new type needs to be allocated, it will be aligned with the beginning of the next logical memory block. The next logical block will depend on your processor. Some processors can align to 8-bit boundaries, while others can only align to 16-bit boundaries. tim Jul 24 at 12:21
5
Next question is: when do I need to save space? Almost never. Unless you're in very limited environments, avoid bit fields. black Jul 24 at 12:28

bitfields are almost never used for flags because if you need to add another one, you will break the ABI z Jul 24 at 12:31
1
As an addition: it behaves more like a boolean: you can write flags.is_keyword == flags.is_extern ( compare with ((flags & IS_KEYWORD) == 0) == ((flags & IS_EXTERN) == 0) ). On the other hand, with traditional bitfields you can check multiple values with one compare statements: (flags & (IS_KEYWORD IS_EXTERN)) == IS_KEYWORD (it means IS_KEYWORD but not IS_EXTERN) GaborSch Jul 24 at 12:32

@GaborSch "like boolean" not absolutely true, you can have values larger than 1. But that is a rarely used use case. rioki Jul 24 at 12:35
show 1 more comment
up vote
6
down vote
Another place where bitfields are common are hardware registers. If you have a 32 bit register where each bit has a certain meaning, you can elegantly describe it with a bitfield.

share|improve this answer
answered Jul 24 at 12:19

undur_gongor
7,27821437
add a comment
up vote
3
down vote
why do we need to use bit-fields'?

When you want to store some data whose can be stored less than byte those kind of data can be coupled in structure using Bit fields. In embedded word, When one 32 bit world of any register has different meaning for different word then also you can use bit fileds to make them more readable.

I found that bit fields are used for flags. Now I am curious, is it the only way bit-fields are used practically?

No this not the only way. You can use it in other way also.

Do we need to use bit fields to save space?

Yes.

As I understand only 1 bit is occupied in memory, but not the whole unsigned int value. Is it correct?

NO. Memory only can be occupied in multiple of byte only.

share|improve this answer
answered Jul 24 at 12:17

Mr.32
7,034855102
add a comment
up vote
2
down vote
To answer the parts of the question no-one else answered:

Ints not Shorts

The reason to use ints rather than shorts etc is that in most cases no space will be saved by doing so.

Modern computers have a 32 or 64 bit architecture and that 32 or 64 bits will be needed even if you use a smaller storage type such as a short.

The smaller types are only useful for saving memory if you can pack them together (for example a short array may use less memory than an int array as the shorts can be packed together tighter in the array). For most cases when using bitfields this is not the case.

Other uses

Bitfields are most commonly used for flags, but there are other things they are used for. For example one way to represent a chess board used in a lot of chess algorithms is to use a 64 bit integer to represent the board (8*8 pixels) and set flags in that integer to give the position of all the white pawns. Another integer shows all the black pawns, etc.

share|improve this answer
answered Jul 24 at 13:39

Tim B
20k51947
add a comment
up vote
2
down vote
Bit fields are for saving memory space. It is used where there is memory constraint. eg) while programming in embedded systems.

But this should be used only if extremely required.

Because we cannot have the address of a bit field. So address operator & cannot be used with them.

share|improve this answer
answered Jul 24 at 15:23

rohit
414
add a comment
up vote
2
down vote
We use bit fields mostly (though not exclusively) for flag structures - bytes or words (or possibly larger things) in which we try to pack tiny (often 2-state) pieces of (often related) information.

In these scenarios, bit fields are used because they correctly model the problem we're solving: what we're dealing with is not really an 8-bit (or 16-bit or 24-bit or 32-bit) number, but rather a collection of 8 (or 16 or 24 or 32) related, but distinct pieces of information.

The problems we solve using bit fields are problems where "packing" the information tightly has measurable benefits and/or "unpacking" the information doesn't have a penalty. For example, if you're exposing 1 byte through 8 pins and the bits from each pin go through their own bus that's already printed on the board so that it leads exactly where it's supposed to, then a bit field is ideal. The benefit in "packing" the data is that it can be sent in one go (which is useful if the frequency of the bus is limited and our operation relies on frequency of its execution), and the penalty of "unpacking" the data is non-existent (or existent but worth it).

On the other hand, we don't use bit fields for booleans in other cases like normal program flow control, because of the way computer architectures usually work. Most common CPUs don't like fetching one bit from memory - they like to fetch bytes or integers. They also don't like to process bits - their instructions often operate on larger things like integers, words, memory addresses, etc.

So, when you try to operate on bits, it's up to you or the compiler (depending on what language you're writing in) to write out additional operations that perform bit masking and strip the structure of everything but the information you actually want to operate on. If there are no benefits in "packing" the information (and in most cases, there aren't), then using bit fields for booleans would only introduce overhead and noise in your code.

share|improve this answer
edited 8 hours ago

answered Jul 24 at 15:14

Theodoros Chatzigiannakis
7,2842735
add a comment
up vote
2
down vote
A good usage would be to implement a chunk to translate to-and from-base64 or any unaligned data structure.

struct {
unsigned int e1:6;
unsigned int e2:6;
unsigned int e3:6;
unsigned int e4:6;
} base64enc; //I don't know if declaring a 4-byte array will have the same effect.

struct {
unsigned char d1;
unsigned char d2;
unsigned char d3;
} base64dec;

union base64chunk {
struct base64enc enc;
struct base64dec dec;
};

base64chunk b64c;
//you can assign 3 characters to b64c.enc, and get 4 0-63 codes from b64dec instantly.
This example is a bit naive, since base64 must also consider null-termination (i.e. a string which has not a length l so that l % 3 is 0). But works as a sample of accessing unaligned data structures.

Another example: Using this feature to break a TCP packet header into its components (or other network protocol packet header you want to discuss), althought it is a more advanced and less end-user example. In general: this is useful regarding PC internals, SO, drivers, an encoding systems.

Another example: analyzing a float number.

struct _FP32 {
unsigned int sign:1;
unsigned int exponent:8;
unsigned int mantissa:23;
}

union FP32_t {
_FP32 parts;
float number;
}
(Disclaimer: Don't know the file name / type name where this is applied, but in C this is declared in a header; Don't know how can this be done for 64-bit flaots since the mantissa must have 52bits and -in a 32bit target- ints have 32 bits).

Conclusion: As the concept and these examples show, this is a rarely used feature because it's mostly for internal purposes, and not for day-by-day software.

share|improve this answer
edited 2 hours ago

answered Jul 24 at 15:20

Luis Masuelli
1,805313
add a comment
up vote
0
down vote
To utilize the memory space we can use bit fields.

As far as i know in Real world programming if we require we can use booleans instead of declaring it as integers and then making bit field.

share|improve this answer
answered Jul 24 at 12:14

Srinivas
9415
1
"In real world", booleans will normally be more than a bit. undur_gongor Jul 24 at 12:16
add a comment
up vote
0
down vote
If it also is values we use often, not only do we save space, we can also gain peformance since we do not need to pollute the caches. However caching is also the danger in using bit fields since concurrent reads and writes to different bits will cause a data race and updates to completely separate bits might overwrite new values with old values..

share|improve this answer
answered Jul 24 at 12:23

Ghaban
11
add a comment
up vote
0
down vote
You can use them to expand the number of unsigned types that wrap. Ordinary you would have only powers of 8,16,32,64... , but you can have every power with bit-fields.

struct a
{
unsigned int b : 3 ;
} ;

struct a w = { 0 } ;

while( 1 )
{
printf("%u\n" , w.b++ ) ;
getchar()

def traceit(frame, event, trace_arg):
global stepping

if event == 'line':
if stepping or frame.f_lineno in breakpoints:
resume = False
while not resume:
print(event, frame.f_lineno, frame.f_code.co_name, frame.f_locals)
command = input_command()
resume = debug(command, frame.f_locals)
return traceit
What is the meaning of the last line in the code?

EDIT:

def remove_html_markup(s):
tag = False
quote = False
out = ""

for c in s:
if c == '<' and not quote:
tag = True
elif c == '>' and not quote:
tag = False
elif c == '"' or c == "'" and tag:
quote = not quote
elif not tag:
out = out + c
return out

def main():
print (remove_html_markup('xyz'))
print (remove_html_markup('"foo"'))
print (remove_html_markup("'foo'"))

# globals
breakpoints = {9: True}
stepping = False

def debug(command, my_locals):
global stepping
global breakpoints

if command.find(' ') > 0:
arg = command.split(' ')[1]
else:
arg = None

if command.startswith('s'): # step
stepping = True
return True
elif command.startswith('c'): # continue
stepping = False
return True
elif command.startswith('q'): # quit
sys.exit(0)
else:
print ("No such command", repr(command))

return False

commands = ['s', 's', 's', 'q']

def input_command():
#command = raw_input("(my-spyder) ")
global commands
command = commands.pop(0)
return command

def traceit(frame, event, trace_arg):
global stepping

if event == 'line':
if stepping or frame.f_lineno in breakpoints:
resume = False
while not resume:
print(event, frame.f_lineno, frame.f_code.co_name, frame.f_locals)
command = input_command()
resume = debug(command, frame.f_locals)
return traceit

# Using the tracer
sys.settrace(traceit)
main()
sys.settrace(None)
python
share|improve this question
edited Aug 8 at 17:45

RWeb
255
asked Aug 8 at 13:40

user3080029
14310
7
What happens? The same thing that happens when you return anything else. Functions are objects just like ints and strings. Kevin Aug 8 at 13:42
3
It's not clear what use it is to return a reference to the function when you call it, but it's certainly straightforward enough. chepner Aug 8 at 13:43

Why would you do it though? ojblass Aug 8 at 13:43
1
Nothing useful. IanAuld Aug 8 at 13:44

I am doing a course on Udacity and the lecturer has this line in the code from the beginning. I don't know why. I have enclosed the entire program now. user3080029 Aug 8 at 13:45
show 4 more comments
4 Answers
activeoldestvotes
up vote
16
down vote
accepted
A function is an object like anyone else, so there's no problem in returning itself. For example, it allows repeated calling on the same line:

traceit("abc", "def", None)("ghi", "jkl", 3)("mno", "pqr", 4.3)
Edit: sys.settrace sets the global tracing function, that is invoked every time a local scope is entered to ask for a local tracing function. Here it returns itself, to handle all the tracing in the same function.

See https://docs.python.org/2/library/sys.html#sys.settrace for details.

share|improve this answer
edited Aug 8 at 13:54

answered Aug 8 at 13:46

Matteo Italia
52.6k653121

The key here is that it is not a pure function, but has side effects, that is what you want. Now, I wouldn't use it in real code, though. Davidmh Aug 8 at 13:57

@iwin: if you think about it, it's just a consequence of being able to return a function object; imagine it with some extra parentheses, like ((traceit("abc", "def", None))("ghi", "jkl", 3))("mno", "pqr", 4.3). Matteo Italia Aug 8 at 19:57
3
That's very clever. Looks like a lisp/haskell hacker at work. Patrick Collins Aug 8 at 22:15
add a comment

up vote
9
down vote
Since all functions in Python are created as objects, it returns a reference to the function.

It may be passed into another function later in the code or called with parameters as you could with any function.

def a(str):
print str
b = a # Assign an instance of a to b
b('hello') # Call b as if it were a

print type(b)
Prints:

hello

share|improve this answer
edited Aug 9 at 19:06

answered Aug 8 at 13:43

iwin
625116
1
an instance of the function, or just the function? Do functions even have instances? immibis Aug 9 at 9:00

Edited, should probably have said a reference. iwin Aug 9 at 19:06
add a comment
up vote
7
down vote
https://docs.python.org/2/library/sys.html#sys.settrace

settrace allows you to pass a function to use as a debugger. Every time a new scope is entered, the function you passed is called. It needs to return a function that should be used for debugging inside that scope.

Since the writer of that code, wanted to always use the same function, the function returns itself.

Relevant bit from the link:

The trace function is invoked (with event set to 'call') whenever a new local scope is entered; it should return a reference to a local trace function to be used that scope, or None if the scope shouldnt be traced.

The local trace function should return a reference to itself (or to another function for further tracing in that scope), or None to turn off tracing in that scope.