Application of bitwise operators in JavaScript

First of all let us revise what bitwise operators are and why you should comprehend them in 2017. Bitwise operators are operators that work on a bit or two bits (comparing them and giving a result based on the comparison) at a time.

AND ( & ) will  be 1 only if both of the bits are 1, otherwise it will be 0.
Example (all combinations): 1&1=1;  1&0=0;  0&1=0;  0&0=0;

OR ( | ) will be 1 if there is a 1 present when comparing two bits,
Example (all combinations): 1|1=1;  1|0=1;  0|1=1;  0|0=0;

XOR ( ^ ) is 1 only if one bit is 1 and the other is 0 no matter the order (1 XOR 0 =1)
(0 XOR 1=1)

NOT ( ~ ) if the bit is 0 it will go to 1 if it is 1 it will go to 0. In this case there is no comparison with other data. If you have an integer, let’s say 5 which is 0101 then the NOT will bring it to 1010.

To see the truth tables go to this website
Practical applications of bitwise operators (real life):
0X1 represents 1 in hexadecimal.


  • We check if the value is odd. If it is, the program returns true it’s not (if it is even) then the program returns false:


(value & 0x1) > 0

Explanation: Let’s say we have a value of 8 and on the other side we have 0x1. We convert them to binary numbers (that’s what the computer only understands at the most bottom level). We write the numbers one below the other and start the calculation from the most right bit to the most left bit (refer to the and operator above)

1000
0001


0000

The result is 0000 which is 0 in denary (decimal ). Zero is not greater than zero so the expression returns false. Which means that the number is even.

JS code:

console.log((8 & 0x1) > 0)
  • Use them for data encryption (encryption is all about bitwise operators)

a = 1903349;
b = 4542345;
c = 5834533;
hash = a ^ b ^ c;

The numbers will be converted to binary and will be hashed (they will be transformed in some boolean XOR equivalent data)

Conclusion:

Bitwise operators are rarely used in JavaScript (as far as I’ve seen in 5 years of coding). I suppose interviewers use them for questions for future employees to see how deep the candidate went with their programming knowledge. Still, it is good to know them because once you see them and maybe have to do something with them you will have the basic knowledge in your head and solving the problem in front of you will require less time and frustration.

So, when doing operation with bitwise operators which are nothing else but boolean operations, always have in mind the truth tables which are easy to understand and learn.

My opinion is, try to avoid them because your code looks incomprehensible to others who may in the future maintain your application. The more clearer you are the better for everyone else.

Programming every day usage differences PART 2

Difference between name-spaces and classes?

Namespaces represent scopes {} where variables, classes, structs and other types reside. Classes are just types which also have to reside inside of a scope and this scope is called namespace. If you want to look at it as a hierarchy, namespaces go first here after that all the other elements/types go, in this case classes.

Other thing which should be mentioned are:

– You can reopen namespaces unlike classes

– You can create an instance of classes unlike with namespaces

– Namespaces can be unnamed unlike with classes which must have a name.

Difference between classes and objects?

Classes and objects are the “same thing”. Basically this is a parameter-argument problem. Classes can be considered as when writing a function. Once you call that class (instantiate) the class becomes an Object.

Difference between arrays and lists?

Both of them can store multiple values and that’s their purpose, to store multiple values. Arrays, however have a fixed storage, so once you declare them you cannot add more cells to it whereas lists are re-sizable.  The other important thing is that arrays are more efficient since they are primitive types and do not need a wrapper around them. List’s represents interfaces (not primitive types) and interfaces have therefore multiple implementations.

Difference between inheritance and interfaces?

Inheritance assumes having an existing class (let’s say a base class, general class like human) which will then be adopted by the newly created class which is related to the base (existing) class and therefore the new class as now access to all properties and methods from the inherited class. It is easier to build the new class or just extend it so it serves to its purpose.

Interface can be seen as blocks or scopes which contain unimplemented variables and methods. A class can inherit multiple interfaces whereas only one class can be inherited. There is no method implementation inside an interface. This is done inside the class once the interface is inherited by it.

Note: The reason why you can’t inherit multiple classes is because you could get a collision between two elements, for example methods. Let’s assume that you can inherit two classes and let the first be “Automobile” class and the second “Robot” class. Suppose both methods have a same method called Run(); When you try to call the method Run() which one should be called? Robots class method or Automobile class method. Because of such problem (which was quite expressed/conspicuous in c++ language) code engineers of languages C# and Java ect. decided not to allow multiple inheritance.

Difference between switch statement, if statements and ternary operators?

There isn’t any better performance in any of the above. Use whatever you like. However it is advised to use switch statement if there are more than 6 if’s. Ternary operators just give a concise syntax and it looks better.

Difference between multidimensional array and jagged array?

Multidimensional arrays are fixed arrays. Once you declare it you are done. Jagged arrays are arrays which contain arrays. This can be also said for the multidimensional array but every row has a same size as does column. Jagged arrays row and column do not have to have same sizes.

Jagged arrays are faster than multidimensional arrays.

Understanding image rendering (digital image theory)

– When we come close to the TV for example, we can see the little squares. These squares are actually pixels if we then approach really close to a smartphone e.g iPhone 4s we will see that we can’t actually see these little squares or maybe we can but with trying really hard. From this, we can conclude that the iPhone has a GREATER PPI (points per inch) inch=2.54cm. So in the case of the iPhone pixels are really tiny, if talking about the TV the pixels are BIGGER! The TV doesn’t t have the equal density as the iPhone because we are watching it at greater range.

– When you are looking at TV at a close range you cannot actually see the pixels but you can see the sub pixels (group of pixels).

– The greater density of the pixels inside an image the more alive the image looks (great density-better picture).

– There exists a gap between pixels.

– Calculating the ppi (pixels per inch) –> first row * column to get the pixel size and then multiply the x inch width and y inch height and you get the area of the display . And now to get the PPI you divide the pixel size with display surface.

– Dots per inch refers to the resolution of a computer printer.

– When talking about PPI in printing 300 is outstanding, as sharp as most printers can print 100 is adequate everything below isn’t good.

All displays are made of from pixels whether it’s a laptop monitor, TV, smartphone etc… Likewise, if we can see the display in color it means that we are at least talking about rgb (red, green, blue channels) each of them has 8 bits and each channel has 2 to the power of 8 possible combinations by mixing these combinations we can get every of the 16 mil colors, also there is the argb mode where a represents a channel as well but more on that later.

Digital image is a rectangular grid of pixels  or “picture elements” it exists as an array of BYTES in the computer’ s RAM memory (this means that every array cell starting from num. 0 to array-length-1 has 1 byte inside of each cell! Important for programming. Fetching the amount of bytes can be done by using the Length property in C# for example).

Pixels are small tiny dots, rectangles or squares they can’t be physically measured and neither can be the distance between them, well it can but it’s not the case for every image that the distance between each pixel will be the same, they are considered as abstract (it doesn’t exist, well it does exist but in a digital way and can be modified and deleted).

Image resolution: refers to image quality and image size specified by the number of pixels but in fact the only attribute that counts is the number of pixels.

Pixels per centimeter (ppcm), Pixels per inch (PPI) or pixel density is a measurement of the resolution of devices in various contexts: typically computer displaysimage scanners, and digital camera image sensors. For example, a 15 inch (38 cm) display whose dimensions work out to 12 inches (30.48 cm) wide by 9 inches (22.86 cm) high, capable of a maximum 1024×768 (or XGA) pixel resolution, can display around 85 PPI in both the horizontal and vertical directions.

Important hints

  • re-sampling = pixels change
  • resizing = pixels do not change, changing the width and the height but the pixels stay the same, they group together
  • aspect ratio 16:9 in units

 

  • our eye can distinguish 10 mil. Colors rgb gives us more than 16 mil.
  • image compression 8×8 pixels in blocks, more is not good
  • you can resize the picture by decreasing the width and height but you can’t reverse the process, well you can but it will be blurred.
  • 720, 1080 YouTube.

Links:

Programming every day usage differences PART 1

Difference between methods and functions?

When talking about object oriented programming (OOP) then we are using methods. Methods are defined inside of classes. Every “method” defined outside of a class is called a function. Java is a typical example where functions do not exist since Java is OOP. In C++ we both have functions and methods.

Basically in OOP languages we talk about methods in languages which are not OOP we talk about functions.

Difference between parameters and arguments?

When defining a function/method we are talking about parameters if we want to use them. Once we pass data to these parameters (on function/method call) we talk about giving arguments to that function. It’s important to mention that parameters and later the arguments that we pass to the method are value types by default. In C# If we want the parameter, the method parameter to become a reference type then we have to write the keyword “ref” inside the method parameter and also when calling the method and giving arguments to it we have to specify the ref keyword.

Difference between variable post-increment and pre-increment?

Code sample:

int y;

int x = 2;

y = x++;// or y=x=(x+1) , y stores x <strong>immediately</strong> and THEN x is being incremented y=2 here

y=x;// if you would go now and write this line you would see that y=3;

// with pre-increment there is nothing much being explained

// first the value is incremented and thus it is stored in the variable y

int y;

y=2;

y=++x;// y=3

I think that everything is pretty much clear with this example especially with the little equations and the comments afterwards (I wouldn’t want to repeat myself).

Difference between foreach and for loop?

In terms of performance I must quote the following (taken from stackoverflow):

Patrick Smacchia blogged about this last month, with the following conclusions:

  • for loops on List are a bit more than 2 times cheaper than foreach loops on List.
  • Looping on array is around 2 times cheaper than looping on List.
  • As a consequence, looping on array using for is 5 times cheaper than looping on List using foreach (which I believe, is what we all do).

Concerning the usage of this loops. When iterating through objects it is better to use foreach loop (it’s nicer). When working with primitive value types then use for loop. In functional programming the for loop is “everything”. Other than that it entirely depends on you. Foreach loops are massively used when iterating through objects.

Difference between explicit and implicit cast?

Example:

int i = 2;

float a = i;        // Implicit

float b = (float)i; // Explicit

I believe that the “image” above is more than enough to describe the explicit and implicit in programming. If not, then you can add the following: Implicit automatically parses the other data type and stores in in the other one if possible. An explicit casts demands additional “functions” to parse the data to the other one if possible.

Difference between structures and classes?

The main difference between classes and structures are when assigning parameters dynamically to structures (example: modifying the struct variables through a method) we can see that the value does not change! From [2] we can conclude that structures are value types. Whereas if we do the same thing with a class (trying to change a class variable through a method) we will see that the class variable will change! From [2] we can conclude that classes are reference types. Apart from that structs can’t be inherited by a another class and are used to store small amount of data inside them in particular.

Difference between private, public and protected?

Since this is the far best quick explanation online, I decided to copy and paste it and not to evaluate further.

public

The type or member can be accessed by any other code in the same assembly or another assembly that references it.

private

The type or member can only be accessed by code in the same class or struct.

protected

The type or member can only be accessed by code in the same class or struct, or in a derived class.

Stack vs Heap

I’ve read lot of articles on-line prior on posting about this topic. I will try to combine various articles which talk about it and try to explain it in an interesting and comprehensible manner.

I believe everyone who’s starting or has programmed for some amount of time without looking at the theory too much, has heard of the term stack, the term heap is usually less heard.

After reading quite a bit of both I can say that there are words which are often misinterpreted by many programmers. I’ll try to do my best and not to make any assumptions neither to place some words in a false context.

STACK

A stack is a memory place/location where variables which a function executes (int, string, char, bool…) are stored. You can think of a box which can add variables inside and also remove them. When a function executes (we are talking here about any function which can be the main() function which is always executed when a program runs and other functions that we have defined in the code and are calling them inside the main() function) all the variables which are inside that function are stored on the stack. We say that “they are pushed onto the stack”. After the function completes, the variables inside the stack are pushed out of the stack, they are removed from it.

Every stack has a fixed location at the beginning, however this can easily change once variables start to kick in and the stack get’s bigger, the memory pointer is displaced to indicate the current extent of the stack. Remember that when new elements are added to the stack they are always placed on top that box called the stack and the old ones do not get pushed out, they are removed once the function is done with it’s execution only then is the stack freed from the variables that the function contained.

The good thing that we take for granted today is that the memory stack is managed automatically, this means that we don’t have to reserve it manually or free it once we do not need the variables anymore.

Variable scope: also all the variables that are stored on the stack are local not global. This means that the variables lifetime is temporary, after the function returns those variables are immediately destroyed as mentioned earlier.

The stack is also called LIFO (last in first out).

One last thing to mention is the stack-overflow event which can occur if the stack’s capacity get’s exceeded. After the event occurs, the programs crashes.

HEAP

A heap is also a memory place/location where objects are stored. Often people use the term dynamic memory allocation (don’t think now that the stack is then also referred to as a static memory allocation, this is completely false, we will talk about this in another article). The good thing about it is that you can allocate and deallocate objects at any time and how much you want.  As you can see by now the heap is used to store bigger data sets and complex data which are objects. The heap is not arranged like the stack, we can say that the objects are thrown around randomly, you can add and remove the object whenever you want there is no top object like there is in a stack.

Variable scope: also all the variables that are stored on the heap are global not local variables. This means that the variables lifetime is not temporary.

This is pretty much it about the heap. Please read the article about the Garbage Collector to get greater knowledge on how and why are objects removed from the heap. (url: https://programmingcroatia.wordpress.com/2015/08/15/garbage-collector/)

To make a conclusion, here is a useful list  about the PROS & CONS taken from stackoverflow (url: http://stackoverflow.com/questions/79923/what-and-where-are-the-stack-and-heap)

Stack:

  • Stored in computer RAM just like the heap.
  • Variables created on the stack will go out of scope and automatically deallocate.
  • Much faster to allocate in comparison to variables on the heap.
  • Implemented with an actual stack data structure.
  • Stores local data, return addresses, used for parameter passing
  • Can have a stack overflow when too much of the stack is used. (mostly from infinite (or too much) recursion, very large allocations)
  • Data created on the stack can be used without pointers.
  • You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.
  • Usually has a maximum size already determined when your program starts

Heap:

  • Stored in computer RAM just like the stack.
  • Variables on the heap must be destroyed manually and never fall out of scope. The data is freed with delete, delete[] or free
  • Slower to allocate in comparison to variables on the stack.
  • Used on demand to allocate a block of data for use by the program.
  • Can have fragmentation when there are a lot of allocations and deallocations
  • In C++ data created on the heap will be pointed to by pointers and allocated with new or malloc
  • Can have allocation failures if too big of a buffer is requested to be allocated.
  • You would use the heap if you don’t know exactly how much data you will need at runtime or if you need to allocate a lot of data.
  • Responsible for memory leaks

GOOD ARTICLES FOR FURTHER LEARNING: 

Pointers (playing with pointers in C)

When I started programming (first language in use:C#) I new that pointers existed but I haven’t really had the time to tackle that field although I really wanted to, but somehow ignored that for a while. In C# I didn’t need pointers for anything, you could to everything without them. Later when I was helping my former high school colleague with C I realized that I will have to learn them one way or the other to help him better understand programming and eventually get a better grade.

I think that everyone has heard of pointers as being a really complicated field to grasp so I took extra caution when started to learn them. I must specify the link where I picked the stuff pretty quickly is really awesome and you will see immediately that the author of the article really took some time to explain them and even made a little quiz which is, again, awesome (he uses c++ but this isn’t relevant in order to understand them): Click here

Here goes my explanation on pointers:

You can think of pointers as arrows which hold an address and therefore the arrow knows where to go. Pointers point to a memory location which stores data. Bear in mind that he computer memory consist of small cells everyone having the length of 1 byte (8bits) and each cell has a unique address. REAL DEFINITION: a pointer is a variable whose value is the address of another variable (definition url: click here)

If you have ever written a decent ms office word article which involves footnotes or if you think of the Wikipedia numbers that are placed at the end of a sentence usually after the dot(.). When you click on the number it will lead you to some further explanation about the marked sentence which is at the end of the Wikipedia document (the further explanation is often accompanied by a link). the little number that you clicked on leads you to some other value in this case associated with the little clicked number. We can say that the little number contains an address which new where to point if clicked. This is exactly how pointers work. They are storing a value which is an address which leads you to another value. To make it 100% simple: they are addresses and everyone knows what addresses are for in real life.

Okay, why do we use pointers, why don’t we just directly store values inside the memory?

Before answering this question I must tell you what I always heard about pointers. Experienced programmers were always saying that pointers are fast. I’ll never forget that because that is the only thing that I’ve heard about pointers from someone else. Well, the reason why there are fast would explain their usage wouldn’t it?

So why use them?

answer: because they save memory and time.

Okay, so how do they safe memory?

Answer: remember what the real definition of pointers is? Pointers store the address of the variable which points to the storage location. Just imagine having a large chunk of data. let this big data be an array. If you want to copy this array to another array and not use pointers you would most definitely store all of the elements of the previous array to a new array rather than doing that you can use the advantage of pointers and create a pointer which will hold the address of the array thus not creating another array and consuming a lot of memory again. Also the memory is heavily connected with the time variable. When you occupy memory it definitely takes up some time. Now, think of populating memory with a lot’s of data. This would take a pretty much amount of time and you don’t want this process to happen multiple times for the same data.

Okay, so now we can see that pointers are efficient, now how do they work and how do you use them?

Answer:

Example 1:

    int *p;
    int a=8;
    p=&a;
    a=5;
    printf("%d",*p);

First to clear things up for real beginners. the symbol (*) means: fetch (get) the value of the pointer p. the symbol (&) means: fetch the address of the variable which is located right after the & symbol.

So, once again value=*,  address=&

The above code has a pointer p declared after that we are storing an integer 8 in variable a. The line “p=&a” means that we are giving the address to the pointer to point! This is what pointers are for, they are always storing the address of a specified variable. We discussed that previously.

Here is a little illustration for that:

The most important thing that you have to remember here is that a pointer always points to a memory location which was defined previously by giving the address to the pointer. This means, no matter how much the value of a location changes which a pointer points to, the pointer will always get the current value of that location. Let’s say that after reserving a space (certain amount of memory) and then declaring a pointer to point to this reserved space, you can alter that location numerous amount of time and the last value specified for this location will be the value of the pointer since it point’s at it always.

See how pointers are easy actually?

Let’s put some more examples:

Example 2:

int a = 5, b = 10;
int *p1, *p2;
p1 = &a;
p2 = &b;
*p1 = 10;
printf("%d", a);

In this example, you can see that you can change the value of a variable by not only changing it to just put another value in it, like you would normally do, for example: a=3 (a variable changed to value 3). You can also modify it by putting it in a pointer *p1 = 10;. This line of code changed variable a from 5 to 10 because earlier, to be more precise at line 3 we said that p1=&a;, and by that we stored the address of a inside p1. Now, every-time we give another value to p1 we will automatically change the value of variable a.

Example 3:

int array[]={1,2,4,7,9};
int *p;
p=&array[3];
*p=10;
printf("%d", array[3]);

We can see that the same applies for an array as well. We’ve declared an array and a pointer p. Next we gave the variable p the address of the 4th element in the array and after that we changed it to 10 using a pointer. Now the array and index are both equal to 10 instead of 7.

This was an introduction to pointers. We mentioned their usage benefits and how to use them in code. Later articles will cover double pointers (pointers which point to pointers which then point to the value, I think you already understand double pointers), functions and pointers as arguments in a function and some more “confusing” pointers code.

Garbage collector

Taken from wikipedia, url: https://en.wikipedia.org/wiki/Garbage_collection_(computer_science)

“In computer science, garbage collection (GC) is a form of automatic memory management. The garbage collector, or just collector, attempts to reclaim garbage, or memory occupied by objects that are no longer in use by the program”

The above definition says all. If you are not dealing with the actual memory in programming then I believe this is enough to know about the GC. Of course other stuff will be mentioned.

When I was answering questions in the C# section at Daniweb I often encountered the word  GC. Some users always said things like: “when the garbage collector kicks in”. This get’s us to a new question and that is, when does the garbage collector really kick in?

The garbage collector (consider it being a program) kicks in, acts, get’s in charge of things when the heap gets full. This means when there is no place left for a new object to populate the heap. Please do not take this for granted, this is just for better understanding when the garbage collector does it’s job. For more on the garbage collector and heaps generation please read the first paragraph on stack-overflow first answer: click here

In real life, We cannot and we should not predict when the garbage collector starts making the free space for new objects. You can also conclude by this that it isn’t necessary to tell the garbage collector when to start (previous to the garbage collector implementation memory had been manually deallocated).

The biggest advantage of the GC is that you don’t need to deallocate objects manually, you don’t have to worry how many objects could the user create at some time and how you should take care of them (how to free space for the new objects and which objects already in action should be pushed aside to the next generation heap).

The disadvantage of the GC is that it also takes up space,  it consumes resources and affects performance. In some previous versions of GC the problem was the so called “blockage/stalls” which meant that the GC rests, doesn’t do anything at some time which obviously isn’t good and affects performance.

Nowadays the GC tries to do as much work as possible in the background while the application runs, although the GC is much more sophisticated than before, it is still hard to maintain lot of memory taken by objects on the heap.

Just to mention that IOS does not implement a GC although being the most desirable. The claim that it affects their performance drastically.

Also there is something called as a Tracing garbage collection which represents a type of garbage collector which job is to trace the objects who will have to be removed by the main GC.