Monday, January 21, 2013

How To Save Files Straight to Google Drive In Firefox


Working with Google Drive is a convenient way to manage files on the go. It’s fast, easy and works on any device with an Internet connection. If you’re frequently downloading files from different sources on the Web, you’ll be glad to know that the Save to Google Drive for Firefox add-on lets you save files directly to Google Drive. This saves you the trouble of having to download the file to your computer and upload it to Google Drive manually if you plan to access it from another device or share it with other Google Drive users.
To get started, download the add-on Save to Google Drive from the Firefox Add-on web page.
After installation, you should get an icon on the top right corner of the browser and a smaller one on the add-on bar located on the bottom. If you don’t see this, press “Ctrl+/” or go to “Menu -> Options” and click on “Add-on Bar”.

If you’re already on the web page where a link to a file is located, then you can go ahead and click on any of the Save to Google Drive icons. If not, navigate to the download page that shows the link first.
The icon will show a popup box with two options: “Add to Queue” and “Analyze this page for links”. Add to Queue is used when you copy a link and paste it into the text field above it. If you don’t want to open a new tab or window for a link, you can right click on a link and click “Copy link location.”

If you want to download more than one link in a page, you can select “Analyze this page for links” to get a list of all links. You can then select the ones you want to send to Google Drive.

After selecting files, you can now go to the add-on’s “Login” tab to log in to Google Drive.

You should see the files in the My Drive folder.

If you don’t see the files, it might still be in the queue. To check this, go back to the add-on pop up box and click on the “Queue Status” tab.
The add-on also lets you turn off notifications of login and save failures as well as setting the default action for right-clicking on the icon on the add-on bar.

To see a list of previously analyzed files, you can go to the “Analyzed files” tab. Here, you can add more files than previously selected to add to the download queue.
Note that some conditions must be met for the add-on to work properly. Links should be direct from the source and are publicly accessible. There also is a 25 mb limit for each file download.
Provided these requirements are met, Save to Google Drive is a brilliant add-on for saving files in the cloud and on-the-go. Whether it’s for sharing with others or for your own use, it can work wonders for saving time and hard drive space.

Friday, January 18, 2013

Structure padding

Data Alignment:
Every data type in C/C++ will have alignment requirement (infact it is mandated by processor architecture, not by language). A processor will have processing word length as that of data bus size. On a 32 bit machine, the processing word size will be 4 bytes.

Historically memory is byte addressable and arranged sequentially. If the memory is arranged as single bank of one byte width, the processor needs to issue 4 memory read cycles to fetch an integer. It is more economical to read all 4 bytes of integer in one memory cycle. To take such advantage, the memory will be arranged as group of 4 banks as shown in the above figure.
The memory addressing still be sequential. If bank 0 occupies an address X, bank 1, bank 2 and bank 3 will be at (X + 1), (X + 2) and (X + 3) addresses. If an integer of 4 bytes is allocated on X address (X is multiple of 4), the processor needs only one memory cycle to read entire integer.
Where as, if the integer is allocated at an address other than multiple of 4, it spans across two rows of the banks as shown in the below figure. Such an integer requires two memory read cycle to fetch the data.

A variable’s data alignment deals with the way the data stored in these banks. For example, the natural alignment of int on 32-bit machine is 4 bytes. When a data type is naturally aligned, the CPU fetches it in minimum read cycles.
Similarly, the natural alignment of short int is 2 bytes. It means, a short int can be stored in bank 0 – bank 1 pair or bank 2 – bank 3 pair. A double requires 8 bytes, and occupies two rows in the memory banks. Any misalignment of double will force more than two read cycles to fetch double data.
Note that a double variable will be allocated on 8 byte boundary on 32 bit machine and requires two memory read cycles. On a 64 bit machine, based on number of banks, double variable will be allocated on 8 byte boundary and requires only one memory read cycle.
Structure Padding:
In C/C++ a structures are used as data pack. It doesn’t provide any data encapsulation or data hiding features (C++ case is an exception due to its semantic similarity with classes).
Because of the alignment requirements of various data types, every member of structure should be naturally aligned. The members of structure allocated sequentially increasing order.



#include <stdio.h>
 
// Alignment requirements
// (typical 32 bit machine)
 
// char         1 byte
// short int    2 bytes
// int          4 bytes
// double       8 bytes
 
// structure A
typedef struct structa_tag
{
   char        c;
   short int   s;
} structa_t;
 
// structure B
typedef struct structb_tag
{
   short int   s;
   char        c;
   int         i;
} structb_t;
 
// structure C
typedef struct structc_tag
{
   char        c;
   double      d;
   int         s;
} structc_t;
 
// structure D
typedef struct structd_tag
{
   double      d;
   int         s;
   char        c;
} structd_t;
 
int main()
{
   printf("sizeof(structa_t) = %d\n", sizeof(structa_t));
   printf("sizeof(structb_t) = %d\n", sizeof(structb_t));
   printf("sizeof(structc_t) = %d\n", sizeof(structc_t));
   printf("sizeof(structd_t) = %d\n", sizeof(structd_t));
 
   return 0;
}
 
Output of Above Program:
For the sake of convenience, assume every structure type variable is allocated on 4 byte boundary (say 0×0000), i.e. the base address of structure is multiple of 4 (need not necessary always, see explanation of structc_t).
structure A
The structa_t first element is char which is one byte aligned, followed by short int. short int is 2 byte aligned. If the the short int element is immediately allocated after the char element, it will start at an odd address boundary. The compiler will insert a padding byte after the char to ensure short int will have an address multiple of 2 (i.e. 2 byte aligned). The total size of structa_t will be sizeof(char) + 1 (padding) + sizeof(short), 1 + 1 + 2 = 4 bytes.
structure B
The first member of structb_t is short int followed by char. Since char can be on any byte boundary no padding required in between short int and char, on total they occupy 3 bytes. The next member is int. If the int is allocated immediately, it will start at an odd byte boundary. We need 1 byte padding after the char member to make the address of next int member is 4 byte aligned. On total, the structb_t requires 2 + 1 + 1 (padding) + 4 = 8 bytes.
structure C – Every structure will also have alignment requirements
Applying same analysis, structc_t needs sizeof(char) + 7 byte padding + sizeof(double) + sizeof(int) = 1 + 7 + 8 + 4 = 20 bytes. However, the sizeof(structc_t) will be 24 bytes. It is because, along with structure members, structure type variables will also have natural alignment. Let us understand it by an example. Say, we declared an array of structc_t as shown below
structc_t structc_array[3];
Assume, the base address of structc_array is 0×0000 for easy calculations. If the structc_t occupies 20 (0×14) bytes as we calculated, the second structc_t array element (indexed at 1) will be at 0×0000 + 0×0014 = 0×0014. It is the start address of index 1 element of array. The double member of this structc_t will be allocated on 0×0014 + 0×1 + 0×7 = 0x001C (decimal 28) which is not multiple of 8 and conflicting with the alignment requirements of double. As we mentioned on the top, the alignment requirement of double is 8 bytes.
Inorder to avoid such misalignment, compiler will introduce alignment requirement to every structure. It will be as that of the largest member of the structure. In our case alignment of structa_t is 2, structb_t is 4 and structc_t is 8. If we need nested structures, the size of largest inner structure will be the alignment of immediate larger structure.
In structc_t of the above program, there will be padding of 4 bytes after int member to make the structure size multiple of its alignment. Thus the sizeof (structc_t) is 24 bytes. It guarantees correct alignment even in arrays. You can cross check.
structure D - How to Reduce Padding?
By now, it may be clear that padding is unavoidable. There is a way to minimize padding. The programmer should declare the structure members in their increasing/decreasing order of size. An example is structd_t given in our code, whose size is 16 bytes in lieu of 24 bytes of structc_t.
 

Thursday, January 17, 2013

Linked list vs array

Both Arrays and Linked List can be used to store linear data of similar types, but they both have some advantages and disadvantages over each other.
Following are the points in favour of Linked Lists.
(1) The size of the arrays is fixed: So we must know the upper limit on the number of elements in advance. Also, generally, the allocated memory is equal to the upper limit irrespective of the usage, and in practical uses, upper limit is rarely reached.
(2) Inserting a new element in an array of elements is expensive, because room has to be created for the new elements and to create room existing elements have to shifted.
For example, suppose we maintain a sorted list of IDs in an array id[].
id[] = [1000, 1010, 1050, 2000, 2040, .....].
And if we want to insert a new ID 1005, then to maintain the sorted order, we have to move all the elements after 1000 (excluding 1000).
Deletion is also expensive with arrays until unless some special techniques are used. For example, to delete 1010 in id[], everything after 1010 has to be moved.
So Linked list provides following two advantages over arrays
1) Dynamic size
2) Ease of insertion/deletion
Linked lists have following drawbacks:
1) Random access is not allowed. We have to access elements sequentially starting from the first node. So we cannot do binary search with linked lists.
2) Extra memory space for a pointer is required with each element of the list.
3) Arrays have better cache locality that can make a pretty big difference in performance.

volatile qualifier in C

Objects declared as volatile are omitted from optimization because their values can be changed by code outside the scope of current code at any time. The system always reads the current value of a volatile object from the memory location rather than keeping its value in temporary register at the point it is requested, even if a previous instruction asked for a value from the same object. So the simple question is, how can value of a variable change in such a way that compiler cannot predict. Consider the following cases for answer to this question.

1) Global variables modified by an interrupt service routine outside the scope: For example, a global variable can represent a data port (usually global pointer referred as memory mapped IO) which will be updated dynamically. The code reading data port must be declared as volatile in order to fetch latest data available at the port. Failing to declare variable as volatile, the compiler will optimize the code in such a way that it will read the port only once and keeps using the same value in a temporary register to speed up the program (speed optimization). In general, an ISR used to update these data port when there is an interrupt due to availability of new data
2) Global variables within a multi-threaded application: There are multiple ways for threads communication, viz, message passing, shared memory, mail boxes, etc. A global variable is weak form of shared memory. When two threads sharing information via global variable, they need to be qualified with volatile. Since threads run asynchronously, any update of global variable due to one thread should be fetched freshly by another consumer thread. Compiler can read the global variable and can place them in temporary variable of current thread context. To nullify the effect of compiler optimizations, such global variables to be qualified as volatile


Another use for volatile is signal handlers. If you have code like this:
quit = 0;
while (!quit)
{
    /* very small loop which is completely visible to the compiler */
}
The compiler is allowed to notice the loop body does not touch the quit variable and convert the loop to a while (true) loop. Even if the quit variable is set on the signal handler for SIGINT and SIGTERM; the compiler has no way to know that.
However, if the quit variable is declared volatile, the compiler is forced to load it every time, because it can be modified elsewhere. This is exactly what you want in this situation.

Thursday, January 10, 2013

Low level operations in c

Bitwise Operators in C

Introduction

When you learn to program in a high-level language like C (although C is fairly low-level, as high-level languages go), the idea is to avoid worrying too much about the hardware. You want the ability to represent mathematical abstractions, such as sets, etc. and have high level language features like threads, higher-order functions, exceptions.
High-level languages, for the most part, try to make you as unaware of the hardware as possible. Clearly, this isn't entirely true, because efficiency is still a major consideration for some programming languages.
C, in particular, was created to make it easier to write operating systems. Rather than write UNIX in assembly, which is slow process (because assembly code is tedious to write), and not very portable (because assembly is specific to an ISA), the goal was to have a language that provided good control-flow, some abstractions (structures, function calls), and could be efficiently compiled and run quickly.
Writing operating systems requires the manipulation of data at addresses, and this requires manipulating individual bits or groups of bits.
That's where two sets of operators are useful: bitwise operators and bitshift operators.
You can find these operators in C, C++, and Java (and presumably C#, since it's basically Java). Bitwise operators allow you to read and manipulate bits in variables of certain types.
Even though such features are available in C, they aren't often taught in an introductory level programming course. That's because intro level courses prefer to emphasize abstraction. With many departments using Java, there's a trend to increase what's abstract, and not get into the representation.
For example, some languages have support for stacks, queues, hashtables, and so forth. These "canned" data structures are meant to provide you, the programmer, with objects that perform certain tasks, while relieving you of the tedium and detail of understanding how the data is represented.
Nevertheless, if you intend to do some work in systems programming, or other forms of low-level coding (operating systems, device drivers, socket programming, network programming), knowing how to access and manipulate bits is important.

Generic Bitwise Operations

Bitwise operators only work on a limited number of types: int and char. This seems restrictive--and it is restrictive, but it turns out we can gain some flexibility by doing some C "tricks".
It turns out there's more than one kind of int. In particular, there's unsigned int, there's short int, there's long int, and then unsigned versions of those ints.
The "C" language does not specify the difference between a short int, an int and a long int, except to state that:
   sizeof( short int ) <= sizeof( int ) <= sizeof( long )
You will find that these sizes vary from ISA to ISA, and possibly even compiler to compiler. The sizes do not have to be distinct. That means all three sizes could be the same, or two of three could be the same, provided that the above restrictions are held.
Bitwise operators fall into two categories: binary bitwise operators and unary bitwise operators. Binary operators take two arguments, while unary operators only take one.
We're going to discuss binary operators first, and we'll do in the context of a fake binary operator called @. Thus, we write x @ y to perform bitwise @ on x and y.
Bitwise operators, like arithmetic operators, do not change the value of the arguments. Instead, a temporary value is created. This can then be assigned to a variable. For example, when you write x + y, neither x nor y have their value changed.
Let's assume that we are doing bitwise @ on two unsigned int variables. Let's assume that unsigned ints use 32 bits of memory. We define two variables X and Y where
   X = x31x30....x0
   Y = y31y30....y0
We want to be able to refer to each bit of X and Y, which we do so by writing out the bits by writing the variable name in lowercase and adding the appropriate subscript for thie bit number.
The subscripts follow the convention we've used so far. The least significant bit has a subscript of 0, and is the rightmost bit. The most significant bit has a subscript of N-1 (for N bits), and is the leftmost bit. In this case N = 32 so the MSb has a subscript of 31.
Let's define @1 to be the @ operation performed on two individual bits. @ is performed on all 32 bits simultaneously.
Furthermore, let's call the temporary value created, T. Normally, this temporary value does not have a name. It is generated while the program is running, and used in other computations. Thus, when you write c = a + b, a temporary value is created for the sum a + b, and this temporary value then gets copied into c.
Of course, for efficiency, the temporary value might not be generated, and the value written directly to c. For more complex statements, such as c = (a + b) - d, temporary values are often created to store intermediate results. These temporary values are created by the runtime system, and are not given variable names.
We define Z = X @ Y as:
   zi = xi @1 yi, for 0 <= i <= N - 1 
In words, to compute the ith bit of Z, you should perform the operation on the ith bit of X and ith bit of Y.

Bitwise AND

This makes more sense if we apply this to a specific operator. In C/C++/Java, the & operator is bitwise AND. The following is a chart that defines &1, defining AND on individual bits.
  xi     yi   xi &1 yi
0 0 0
0 1 0
1 0 0
1 1 1
We can do an example of bitwise &. It's easiest to do this on 4 bit numbers, however.
Variable b3 b2 b1 b0
x 1 1 0 0
y 1 0 1 0
z = x & y 1 0 0 0

Bitwise OR

The | operator is bitwise OR (it's a single vertical bar). The following is a chart that defines |1, defining OR on individual bits.
  xi     yi   xi |1 yi
0 0 0
0 1 1
1 0 1
1 1 1
We can do an example of bitwise |. It's easiest to do this on 4 bit numbers, however.
Variable b3 b2 b1 b0
x 1 1 0 0
y 1 0 1 0
z = x | y 1 1 1 0

Bitwise XOR

The ^ operator is bitwise XOR. The usual bitwise OR operator is inclusive OR. XOR is true only if exactly one of the two bits is true. The XOR operation is quite interesting, but we defer talking about the interesting things you can do with XOR until the next set of notes.
The following is a chart that defines ^1, defining XOR on individual bits.
  xi     yi   xi ^1 yi
0 0 0
0 1 1
1 0 1
1 1 0
We can do an example of bitwise ^. It's easiest to do this on 4 bit numbers, however.
Variable b3 b2 b1 b0
x 1 1 0 0
y 1 0 1 0
z = x ^ y 0 1 1 0

Bitwise NOT

There's only one unary bitwise operator, and that's bitwise NOT. Bitwise NOT flips all of the bits.
There's not that much to say about it, other than it's not the same operation as unary minus.
The following is a chart that defines ~1, defining NOT on an individual bit.
  xi   ~1 xi
0 1
1 0
We can do an example of bitwise ~. It's easiest to do this on 4 bit numbers (although only 2 bits are necessary to show the concept).
Variable b3 b2 b1 b0
x 1 1 0 0
z = ~x 0 0 1 1

Uses of Bitwise Operations

Occasionally, you may want to implement a large number of Boolean variables, without using a lot of space.
A 32-bit int can be used to stored 32 Boolean variables. Normally, the minimum size for one Boolean variable is one byte. All types in C must have sizes that are multiples of bytes. However, only one bit is necessary to represent a Boolean value.
You can also use bits to represent elements of a (small) set. If a bit is 1, then element i is in the set, otherwise it's not.
You can use bitwise AND to implement set intersection, bitwise OR to implement set union.
In upcoming notes, you'll learn how to find the value of individual bits of a char or int.

Facts About Bitwise Operators

Consider the expression x + y. Do either x or y get modified? The answer is no.
Most built-in binary operators do not modify the values of the arguments. This applies to logical operators too. They don't modify their arguments.
There are operators that do assignment such as +=, -=, *=, and so on. They apply to logical operators too. For example, |=, &=, ^=. Nearly all binary operators have a version with = after it. 

Bitshift Operators

Did you think that << or >> was invented in C++? That these operators did not exist in C? If so, you're wrong. These operators did exist in C. Of course, they were not the stream insertion and extraction operators. These were bitshift operators.
The bitshift operators take two arguments, and looks like:
  x << n
  x >> n
where x can be any kind of int variable or char variable, and n can be any kind of int variable.
Think of x as a bitstring (since it is), and n as the number of bits to shift left or write. You should be familiar with shifting, because it's a fundamental operation in, say, insertion sort.

Restrictions

Like bitwise operators, you can only perform bitshift operations on x (the left argument) on certain types: in particular, any kind of int and any kind of char.
There are sneaky ways to shift bits even if you use other types (say, float). This involves tricks with casting. We'll see this at the end of these notes.

Operator <<

The operation x << n shifts the value of x left by n bits.
Let's look at an example. Suppose x is a char and contains the following 8 bits.
b7 b6 b5 b4 b3 b2 b1 b0
1 1 0 0 0 1 1 1
If we shift left by 3 bits, the result is:
b7 b6 b5 b4 b3 b2 b1 b0
0 0 0 1 1 1 0 0
When you shift left by k bits then, bi + k = bi. If i + k > N, then bit bi fell off the left edge. If i < K, then bi = 0. In other words the low K bits are all 0's.
That means that as you shift left, the bits on the high end (to the left) fall off, and 0 is shifted in from the right end.

Left shifting is multiplying by 2K

If you shift left on an unsigned int by K bits, this is equivalent to multiplying by 2K. Why is that? Fix your attention to a bit that has a value of 1. Suppose bi = 1 prior to shifting. This bit contributes 2i to the overall value.
If you shift left by K bits, then this 1 will now appear as bi + K. Thus, that bit contributes 2i + K, which is, of course, equal to 2i * 2K (using law of exponents), i.e., it's multiplying by 2K.
Of course, this multiplication can only go so far. For unsigned int, when the first "1" falls off the left edge, the operation has overflowed. That is, you've multiplied by 2K such that the result is larger than the largest possible unsigned int.
Shifting left on signed values also works, but overflow occurs when the most significant bit changes values (from 0 to 1, or 1 to 0).
It's not nearly as obvious that shifting left in 2C would actually multiply by 2. The easiest way to view this is to think about 1C. The difference between 1C and 2C is 1. That means, if you're looking at a negative number, and focus on the bits with 0, they shift when they move to the left. Now, the correponding positive value is computed by flipping the bits (thus, those 0 bits are now 1), and effectively, you're watching 1 bits move left.
Another way to view this is to recall that 2C is equivalent to flipping the bits left of the rightmost 1. Again, if you look at the 0's left of that rightmost 1, they will eventually become 1's and they are shifting to the left.

Operator >>

Left shifting generally creates few problems regardless of type. 0's are shifted from the least significant end, and bits fall off the most significant end. Right shifting causes a few more problems. When shifting to the right for unsigned int, bits fall off the least significant end, and 0's are shifted in from the most significant end. This is also known as logical right shift (logical shifts shift in 0's).
However, with signed int, the story is different. What right shifting does depends on the compiler. One possibility is to shift in 0's, just as unsigned int's do. If this occurs, then you divide by 2K (if you're shifting K bits), but only for non-negative values of x. For negative values, you've made it positive, and it no longer makes sense that this operation is equivalent to dividing by 2K.
Compilers may also shift in the sign bit. Thus, if x is negative, the sign bit is 1, so 1's are shifted from the most significant end. If x is non-negative, 0's are shifted from the most significant end. This is called an arithmetic right shift since the sign bit is shifted in. Thus, if you shift right by K bits, then K 1's or K 0's are shifted in.
Let's look at an example of this. Suppose x looks like before:
b7 b6 b5 b4 b3 b2 b1 b0
1 1 0 0 0 1 1 1
Let's shift right by 3 bits. If the sign bit is shifted in, the result is:
b7 b6 b5 b4 b3 b2 b1 b0
1 1 1 1 1 0 0 0
If 0's are shifted in, the result is:
b7 b6 b5 b4 b3 b2 b1 b0
0 0 0 1 1 0 0 0

Shifting Doesn't Change Values

Here's one of those rather annoying facts about C, that is perfectly consistent with the way C does things. Suppose x = 3 and n = 2. What does the following code do?
  int x = 3 ;
  int n = 2 ;
  x << n ;
  cout << x << endl ; 
What does it print? The answer is 3. The answer is NOT 12.
Why is that? Suppose you were asked to sum x + y. What will happen to x or y? Of course, you know that nothing happens to them. But then where does the sum go? A temporary value is created internally, and that value is typically used to assign to some result or printed.
The same thing happens when you do x << n. It creates a temporary value with a bitshifted version of x, but does not change the value of x.
So, how do you save the change? Simple, just assign it.
  x = x << n ;
  cout << x << endl ; 
This prints out 12 (if x is 3 and n is 2). There's an equivalent way to do this. Use the <<=; operator. Nearly every C binary operator has a version with ='s after it.
  x <<= n ;
  cout << x << endl ; 

Shifting Bits for other types

Suppose you wish to shift left on float variables. The compiler will complain that you can't do this. Bitwise/bitshift operations aren't defined on float variables. So, what can you do?
Trick the compiler.
How do you do that?
Make it think the float is an int.
Here's the wrong way to do it. You can try to cast the float to an int. But if you do this, you have two problems. First, casting creates a temporary value. Even if you save this, the bits will actually change. A float that's cast to an int causes the fractional part to be truncated, and what's more, it changes the representation from IEEE 754 to 2C.
Nevertheless, casting is the right idea. Here's how to do it.
   float x ;
   int * ptr = (int *) (& x) ;
   *ptr <<= n ; // left shift by n bits
You make a pointer that points to the float with same number of bytes, then you shift based on the dereferenced pointer. At this point, when we manipulate *ptr, we're actually manipulating x.

Some facts:
  • Shifting left using << causes 0's to be shifted from the least significant end (the right side), and causes bits to fall off from the most significant end (the left side). This occurs whether the variable is signed or unsigned.
  • Shifting left by K bits is equivalent to multiplying by 2K.
  • Shifting right using >> causes 0's to be shifted from the most significant end (the left side), and causes bits to fall off from the least significant end (the right side) if the number is unsigned. If it's signed, then it's implementation depedendent. It may shift in the sign bit from the left, or it may shift in 0's (it makes more sense to shift in the sign bit).
  • For unsigned int, and sometimes for signed int, shifting right by K bits is equivalent to dividing by 2K (using integer division).
  • Bitshifting doesn't change the value of the variable being shifted. Instead, a temporary value is created with the bitshifted result.

Mask

For our examples, we'll work with 8-bit bitstrings. I could look at 32 bit ints, but they're 32 bits, and that's a lot of bits to write. The principle still apply.
We're going to consider bitstring pattern called a mask. Here's one example of a mask.
b7 b6 b5 b4 b3 b2 b1 b0
0 0 0 0 1 0 0 0
This is a bitstring with exactly one bit that has a value of 1. In this example, b3 = 0.
Similarly, the bitflipped version of this is also considered a mask.
b7 b6 b5 b4 b3 b2 b1 b0
1 1 1 1 0 1 1 1
What's the purpose of a mask? The purpose is to either access an individual bit (or range of bits) or to modify an individual bit (or range of bits). 

Using the Mask

Let's see how we can use this mask to determine whether a bit is set or clear. Before we can do that, perhaps we should define what it means to be set or clear.
  • To set a bit means to make the value of the bit 1.
  • To clear a bit means to make the value of the bit 0.
Suppose you're asked to write a function that returns true if bit i is set, and false if it's clear. We'll call this function isBitISet(). Here's the prototype:
bool isBitISet( unsigned char ch, int i ) ;
Here's the code.
bool isBitISet( unsigned char ch, int i ) 
{
   unsigned char mask = static_cast( 1 << i ) ;
   return mask & ch ;   
}
It looks pretty simple, doesn't it? Create a mask, then use bitwise AND on the character. Here's why it works.
ch b7 b6 b5 b4 b3 b2 b1 b0
mask 0 0 0 0 1 0 0 0
result = ch & mask 0 0 0 0 b3 0 0 0
We don't particularly care what the character looks like. Just assume it's some 8-bit bitstring, b7...b0. To distinguish the character from the mask, let's label the bits of the mask as m7...m0.
The mask has bit m3 set, though 3 was picked arbitrarily. Notice what happens when you bitwise AND the mask and the character.
The bits which are 0 in the mask cause the result to also be 0 (since 0 & bi = 0). Bit b3 is ANDed with the '1' appearing in the mask at position m3. That results in b3.
If b3 = 1, then result is non-zero. If b3 = 0, then result is zero.
The only interesting part is the return type. The result of the AND operation is an unsigned char. We're returning a bool (in C, you'd return an int or a short).
In C++, converting between char, int, and bool rarely requires a cast. Basically, anything that evaluates to 0 for a given type, is false when converted to a bool Anything that evaluates to a non-zero value (which doesn't have to be 1), evaluates to true.

Is Any Bit Set Within a Range?

In the last set of notes, we wrote a C function that would determine whether bit i was set or not. Can we generalize this function? In particular, can we implement the following prototype?
bool isBitSetInRange( char ch, int low, int high ) ;
This function returns true if any bit within bhigh...blow had a value of 1. We assume that low <= high. Note that all bits could be 1, or some bits could be 1, or exactly 1 bit in the range could be 1, and they would all return true. You return false only when all the bits in that range are 0. In order to implement this function, we need to modify the mask. In particular, suppose low = 3 and high = 5, then we would expect the mask to look like:
b7 b6 b5 b4 b3 b2 b1 b0
0 0 1 1 1 0 0 0

How to Create a Mask with a Range

So we want to write code that creates a mask that looks like the one in the previous section. How can we do this? There are at several ways to do this. Method 1 Write a for-loop that checks if bit i is set, from the previous section.
   for ( int i = low ; i <= high ; i++ )
     if ( isBitISet( ch, i )
       return true ;
   // If it didn't return true in the for-loop, then return false
   return false ;
The nice thing about this code is that it reuses the previous code. As a computer science major, the first solution ought to be one that uses an old solution. However, the main drawback is using a loop. If the bitstring had been much longer (say, 32 or 64 bits), using a loop is more inefficient than not using one.
Method 2 This is somewhat complicated, so we'll need to break it down into steps.
  • First, we need to create a mask with the appropriate number of 1's. Suppose we want k 1's. Initially, we'll create a mask with n - k 0's, followed by k 1's. This is easier (for now) than creating the actual mask we need. The question is how to compute k given low and high. This is a classic off-by-one situation. Your first instinct might be high - low. But this would be incorrect. If the index high == low, then high - low == 0.
    That's not what you want. When high == low, you want to test for a single bit, i.e. bhigh (which is the same as blow since high == low). Thus, you want the formula to equal 1, when high == low.
    So, the formula should be high - low + 1.
    Here's the code to do this.
       unsigned char mask = ~0 ;   // creates all 1's, using bitwise negation of 0
       int numOnes = (high - low) + 1 ; 
       int numBits = sizeof( unsigned char ) * 8 ;
    
       // creates (numBits - numOnes) 0's followed by numOnes 1's
       mask >>= ( numBits - numOnes ) ; 
    
  • Then, we need to shift left to place the 1's in the correct spot. The question is how much to shift left. The answer is abit tricky. Here's how to figure the answer. Think about the least significant bit. It's at position b0. It currently has a value of 1. Where should this bit end up? Since it's the rightmost bit, it should be the rightmost 1 when we shift left. And where's the rightmost 1? It's at blow. So we need to shift left by low bits. The remaining 1's shift left with it, and the leftmost 1 should land at bhigh because we computed the number of 1's ahead of time.
       mask <<= low ;
    
So, the entire code to create the mask looks like:
   unsigned char mask = ~0 ;   // creates all 1's, using bitwise negation of 0
   int numOnes = (high - low) + 1 ; 
   int numBits = sizeof( unsigned char ) * 8 ;

   // creates (numBits - numOnes) 0's followed by numOnes 1's
   mask >>= ( numBits - numOnes ) ; 
   mask <<= low ; // shift left group of 1's to correct location
Notice that no loops were used.
The one possible problem we have is the mask being shifted to the right. If we had used a signed char, instead of an unsigned char, we might have had the sign bit shifted in from the left. That would not create the desired mask (instead, it would leave us with all 1's).
So, here's a solution that avoids this problem.

   unsigned char mask = ~0 ;   // creates all 1's, using bitwise negation of 0
   int numOnes = (high - low) + 1 ; 

   // creates (numBits - numOnes) 1's followed by numOnes 0's
   mask <<= numOnes ; 

   // creates (numBits - numOnes) 0's followed by numOnes 1's
   mask = ~mask ;
   mask <<= low ; // shift left the group of 1's to correct location
By left shifting, we guarantee that 0's are shifted in from the right, regardless of whether the type is signed or unsigned. However, we need the additional step of negating the mask to get the pattern we want. This solution avoids using right shifts, thus should be more portable.
Method 3 The previous solution is moderately complicated to think about, though once you get used to the idea, it isn't all that bad.
A third way to produce the mask is to not only use bitshift operators, but also to use subtraction.
Consider the following two masks.
  b7 b6 b5 b4 b3 b2 b1 b0
maskHigh 0 0 1 1 1 1 1 1
maskLow 0 0 0 0 0 1 1 1
maskHigh - maskLow 0 0 1 1 1 0 0 0
So, if we could create a mask with high 1's and a mask with low 1's (as shown above), then subtract, we'd get the desired mask.
How can we get a mask with k 1's? To answer this, answer the following question. Suppose you have 1000 in base 10. This is 1, followed by 3 zeroes. If you subtract 1 from 1000, what do you get? You get 999. Suppose you have 100000. This is 1 followed by 5 zeroes. If you subtract 1 from that, you get 99999.
If you have 1, followed by k zeroes and you subtract 1 from it, then what do you get? You get k 9's.
Now, if this were binary, and you have 1 followed by k zeroes, and you subtract 1, what would you get? You'd get k 1's.
So here's the question. How do get 1, followed by k 0's? You bitshift 1 to the left by k!
  unsigned int mask = 1 << k ;
  mask -= 1 ; // Produces k 1's
So, here's how you get maskHigh and maskLow.
  unsigned char maskHigh = ( 1 << ( high + 1 ) ) - 1 ;
  unsigned char maskLow = ( 1 << low ) - 1 ;
  unsigned char mask = maskHigh - maskLow ;
There is a slight awkwardness when computing maskHigh. We want the leftmost 1 to appear at bhigh. This means when we create the 1, followed by k zeroes, the "1" has to be shifted to bit position bhigh + 1. On the other hand, no such problems occur with maskLow. The string of 1's we want appear in the correct location by shifting 1 to blow.
If you're observant, you'll notice that when we compute mask, we're performing a computation that's of the form (x - 1) - (y - 1). Notice the 1's cancel, and you get (x - y).
So, we can get the mask without subtracting 1, as in:
  unsigned char mask = ( 1 << ( high + 1 ) ) - ( 1 << low ) ;
Which method is perferable? Method 2 is a little complicated, but is completely restricted to bitwise and bitshift operators. The advantage of that is that it works on signed and unsigned quantities.
Method 3 is simpler to understand, but uses subtraction. This turns out to work whether the type is signed or unsigned.

Putting it All Together

Once you create the mask, the code is really simple to check the range.
bool isBitSetInRange( char ch, int low, int high ) 
{
   unsigned char mask = .... ;
   // code to create mask

   return ch & mask ;
}
It's the same as before. This time, however, ch & mask may produce a result that has more than single bit with a value of 1, whereas the mask that checked for bit i being one could only produce a result that has, at most, one bit with a value of 1. However, it doesn't matter how many bits are 1. As long as at least one bit is 1, then the result is non-zero, and thus, the return value is true.

How to Set a Bit

So far, we've written functions to determine the value of individual bits of a number, or to determine if, within some range of bits, whether any bit was set. I'm sure you're interested in actually modifying bits. Once you understand masks, it's easy to modify individual bits.
Here's the prototype of the function we wish to implement.

unsigned char setBit( unsigned char ch, int i ) ;
This will take a character as input, set bi to 1, and return that new character, while leaving the original character untouched (which happens because the original character is passed by value, which means it's a copy of the argument).
Here's the code:

unsigned char setBit( unsigned char ch, int i ) 
{
  unsigned mask = 1 << i ;  // we could cast to unsigned char, just to be safe
  return mask | char ;  // using bitwise OR
}
Let's see how this works on an example:
  b7 b6 b5 b4 b3 b2 b1 b0
ch 1 0 0 0 0 0 1 1
mask 0 0 0 0 1 0 0 0
ch & mask 1 0 0 0 1 0 1 1
Instead of bitwise AND, we use bitwise OR. If you perform bitwise OR on a bit b with 0, you get back bit b. Thus, for all the bit positions in the mask with zero (in the example above, it's every bit except bit b3 in the mask), the corresponding bit position of ch & mask is just the value of the corresponding bit position in ch.
In other words, whereever there's a 0 in the mask, the original bit value in ch is preserved. For example, b7 = 1 in ch and the mask has a 0 in that position. The result ch & mask also has a 1 at that same bit position.
In fact, the only bit position that can potentially change in the result is the bit position that's a 1 in the mask. The mask has a 1 at b3. When you OR a bit b with 1, you get a 1 as a result.
Thus, this causes b3 to be 1 regardless of what b3 is in ch.
This is exactly the effect we're looking for. Setting b3 to 1 in the result, but leaving all other bits unchanged.


Wednesday, January 9, 2013

Big and Little Endian

Basic Memory Concepts

In order to understand the concept of big and little endian, you need to understand memory. Fortunately, we only need a very high level abstraction for memory. You don't need to know all the little details of how memory works.
All you need to know about memory is that it's one large array. But one large array containing what? The array contains bytes. In computer organization, people don't use the term "index" to refer to the array locations. Instead, we use the term "address". "address" and "index" mean the same, so if you're getting confused, just think of "address" as "index".
Each address stores one element of the memory "array". Each element is typically one byte. There are some memory configurations where each address stores something besides a byte. For example, you might store a nybble or a bit. However, those are exceedingly rare, so for now, we make the broad assumption that all memory addresses store bytes.
I will sometimes say that memory is byte-addresseable. This is just a fancy way of saying that each address stores one byte. If I say memory is nybble-addressable, that means each memory address stores one nybble.

Storing Words in Memory

We've defined a word to mean 32 bits. This is the same as 4 bytes. Integers, single-precision floating point numbers, and MIPS instructions are all 32 bits long. How can we store these values into memory? After all, each memory address can store a single byte, not 4 bytes.
The answer is simple. We split the 32 bit quantity into 4 bytes. For example, suppose we have a 32 bit quantity, written as 90AB12CD16, which is hexadecimal. Since each hex digit is 4 bits, we need 8 hex digits to represent the 32 bit value.
So, the 4 bytes are: 90, AB, 12, CD where each byte requires 2 hex digits.
It turns out there are two ways to store this in memory.

Big Endian

In big endian, you store the most significant byte in the smallest address. Here's how it would look:
Address Value
1000 90
1001 AB
1002 12
1003 CD

Little Endian

In little endian, you store the least significant byte in the smallest address. Here's how it would look:
Address Value
1000 CD
1001 12
1002 AB
1003 90
Notice that this is in the reverse order compared to big endian. To remember which is which, recall whether the least significant byte is stored first (thus, little endian) or the most significant byte is stored first (thus, big endian). Notice I used "byte" instead of "bit" in least significant bit. I sometimes abbreciated this as LSB and MSB, with the 'B' capitalized to refer to byte and use the lowercase 'b' to represent bit. I only refer to most and least significant byte when it comes to endianness.

Which Way Makes Sense?

Different ISAs use different endianness. While one way may seem more natural to you (most people think big-endian is more natural), there is justification for either one. For example, DEC and IBMs(?) are little endian, while Motorolas and Suns are big endian. MIPS processors allowed you to select a configuration where it would be big or little endian.
Why is endianness so important? Suppose you are storing int values to a file, then you send the file to a machine which uses the opposite endianness and read in the value. You'll run into problems because of endianness. You'll read in reversed values that won't make sense.
Endianness is also a big issue when sending numbers over the network. Again, if you send a value from a machine of one endianness to a machine of the opposite endianness, you'll have problems. This is even worse over the network, because you might not be able to determine the endianness of the machine that sent you the data.
The solution is to send 4 byte quantities using network byte order which is arbitrarily picked to be one of the endianness (not sure if it's big or little, but it's one of them). If your machine has the same endianness as network byte order, then great, no change is needed. If not, then you must reverse the bytes.

History of Endian-ness

Where does this term "endian" come from? Jonathan Swift was a satirist (he poked fun at society through his writings). His most famous book is "Gulliver's Travels", and he talks about how certain people prefer to eat their hard boiled eggs from the little end first (thus, little endian), while others prefer to eat from the big end (thus, big endians) and how this lead to various wars. Of course, the point was to say that it was a silly thing to debate over, and yet, people argue over such trivialities all the time (for example, should braces line in parallel or not? vi or emacs? UNIX or Windows).

Misconceptions

Endianness only makes sense when you want to break a large value (such as a word) into several small ones. You must decide on an order to place it in memory. However, if you have a 32 bit register storing a 32 bit value, it makes no sense to talk about endianness. The register is neither big endian nor little endian. It's just a register holding a 32 bit value. The rightmost bit is the least significant bit, and the leftmost bit is the most significant bit.
There's no reason to rearrange the bytes in a register in some other way.
Endianness only makes sense when you are breaking up a multi-byte quantity, and attempting to store the bytes at consecutive memory locations. In a register, it doesn't make sense. A register is simply a 32 bit quantity, b31....b0, and endianness does not apply to it.
With regard to endianness, You may argue there's a very natural way to store 4 bytes in 4 consecutive addresses, and that the other way looks strange. In particular, it looks "backwards". However, what's natural to you may not be natural to someone else. The fact of the matter is that the word is split in 4 bytes, and most people would agree that you need some order to place it in memory.

C-style strings

Once you start thinking about endianness, you begin to think it applies to everything. Before you see big or little endian, you may have had no idea it even existed. That's because it's reasonably well-hidden from you. If you do bitwise/bitshift operations on an int, you don't notice the endianness. The machine arranges the multiple bytes so the least significant byte is still the least significant byte (e.g., b7-0) and the most significant byte is still the most significant byte (e.g., b31-24).
So, it's natural to think whether strings might be saved in some sort of strange order, depending on the machine.
This is where it's useful to think about all the facts you know about arrays. A C-style string, after all, is still an array of characters.
Here are some facts you should know about C-style strings and arrays.
  • C-style strings are stored in arrays of characters.
  • Each character requires one byte of memory, since characters are represented in ASCII (in the future, this could change, as Unicode becomes more popular).
  • In an array, the address of consecutive array elements increases. Thus, & arr[ i ] is less than & arr[ i + 1 ].
  • What's not as obvious is that if something is stored in increasing addresses in memory, it's going to be stored in increasing "addresses" in a file. When you write to a file, you usually specify an address in memory, and the number of bytes you wish to write to the file starting at that address.
So, let's imagine some C-style string in memory. You have the word "cat". Let's pretend 'c' is stored at address 1000. Then 'a' is stored at 1001. 't' is at 1002. The null character '\0' is at 1003. Since C-style strings are arrays of characters, they follow the rules of characters. Unlike int or long, you can easily see the individual bytes of a C-style string, one byte at a time. You use array indexing to access the bytes (i.e., characters) of a string. You can't easily index the bytes of an int or long, without playing some pointer tricks (using reinterpret cast, for example, in C++). The individual bytes of an int are more or less hidden from you.
Now imagine writing out this string to a file using some sort of write() method. You specify a pointer to 'c', and the number of bytes you wish to print (in this case 4). The write() method proceeds byte by byte in the character string and writes it to the file, starting with 'c' and working to the null character.
Given that explanation, is it clear whether endianness matters with C-style strings? Hopefully, it is clear.
As an aside, since C++ strings are objects, it may have complicated inner structures, and so it's less obvious what a C++ string would look like when print out to a file. It's well-known what a C-style string looks like (a sequence of characters ending in a null character), which is why I've been careful to call them C-style strings.

Is there a quick way to determine endianness of your machine?

There are n no. of ways for determining endianness of your machine. Here is one quick way of doing the same.
#include <stdio.h>
int main()
{
   unsigned int i = 1;
   char *c = (char*)&i;
   if (*c)   
       printf("Little endian");
   else
       printf("Big endian");
   getchar();
   return 0;
}
In the above program, a character pointer c is pointing to an integer i. Since size of character is 1 byte when the character pointer is de-referenced it will contain only first byte of integer. If machine is little endian then *c will be 1 (because last byte is stored first) and if machine is big endian then *c will be 0.

Memory layout of C program

A typical memory representation of C program consists of following sections.
1. Text segment
2. Initialized data segment
3. Uninitialized data segment
4. Stack
5. Heap

A typical memory layout of a running process
1. Text Segment:
A text segment , also known as a code segment or simply as text, is one of the sections of a program in an object file or in memory, which contains executable instructions.
As a memory region, a text segment may be placed below the heap or stack in order to prevent heaps and stack overflows from overwriting it.
Usually, the text segment is sharable so that only a single copy needs to be in memory for frequently executed programs, such as text editors, the C compiler, the shells, and so on. Also, the text segment is often read-only, to prevent a program from accidentally modifying its instructions.
2. Initialized Data Segment:
Initialized data segment, usually called simply the Data Segment. A data segment is a portion of virtual address space of a program, which contains the global variables and static variables that are initialized by the programmer.
Note that, data segment is not read-only, since the values of the variables can be altered at run time.
This segment can be further classified into initialized read-only area and initialized read-write area.
For instance the global string defined by char s[] = “hello world” in C and a C statement like int debug=1 outside the main (i.e. global) would be stored in initialized read-write area. And a global C statement like const char* string = “hello world” makes the string literal “hello world” to be stored in initialized read-only area and the character pointer variable string in initialized read-write area.
Ex: static int i = 10 will be stored in data segment and global int i = 10 will also be stored in data segment
3. Uninitialized Data Segment:
Uninitialized data segment, often called the “bss” segment, named after an ancient assembler operator that stood for “block started by symbol.” Data in this segment is initialized by the kernel to arithmetic 0 before the program starts executing
uninitialized data starts at the end of the data segment and contains all global variables and static variables that are initialized to zero or do not have explicit initialization in source code.
For instance a variable declared static int i; would be contained in the BSS segment.
For instance a global variable declared int j; would be contained in the BSS segment.
4. Stack:
The stack area traditionally adjoined the heap area and grew the opposite direction; when the stack pointer met the heap pointer, free memory was exhausted. (With modern large address spaces and virtual memory techniques they may be placed almost anywhere, but they still typically grow opposite directions.)
The stack area contains the program stack, a LIFO structure, typically located in the higher parts of memory. On the standard PC x86 computer architecture it grows toward address zero; on some other architectures it grows the opposite direction. A “stack pointer” register tracks the top of the stack; it is adjusted each time a value is “pushed” onto the stack. The set of values pushed for one function call is termed a “stack frame”; A stack frame consists at minimum of a return address.
Stack, where automatic variables are stored, along with information that is saved each time a function is called. Each time a function is called, the address of where to return to and certain information about the caller’s environment, such as some of the machine registers, are saved on the stack. The newly called function then allocates room on the stack for its automatic and temporary variables. This is how recursive functions in C can work. Each time a recursive function calls itself, a new stack frame is used, so one set of variables doesn’t interfere with the variables from another instance of the function.
5. Heap:
Heap is the segment where dynamic memory allocation usually takes place.
The heap area begins at the end of the BSS segment and grows to larger addresses from there.The Heap area is managed by malloc, realloc, and free, which may use the brk and sbrk system calls to adjust its size (note that the use of brk/sbrk and a single “heap area” is not required to fulfill the contract of malloc/realloc/free; they may also be implemented using mmap to reserve potentially non-contiguous regions of virtual memory into the process’ virtual address space). The Heap area is shared by all shared libraries and dynamically loaded modules in a process.

Note: The size command lists the size of the text, data, and bss segments.

Converter mkv to m4v


$ ffmpeg -i input.mkv -vcodec copy -acodec copy -absf aac_adtstoasc output.m4v