Monday, May 3, 2021

Embedded C Interview questions

MORE IMPORTANT QUESTIONS: http://pandyaelectronics.blogspot.com/2021/06/an-ultimate-guide-for-embeddedfirmware.html


 https://sites.google.com/site/embedsystem1/home/interview-questions

https://www.codeproject.com/Articles/6154/Writing-Efficient-C-and-C-Code-Optimization

  • Count-down loops is always better than count-up loops (primarily because, != is faster than <= operation)
  • Loop Unrolling: Small loops can be unrolled for higher performance, with the disadvantage of increased code size.
  • Referring to address of local variable results in unoptimized code: Reason - Compiler will try to optimize by using it's registers for the variables; but when you refer the address, it cannot allocate a register and rather use memory (and there-by resulting in memory operation)
  • Reduce global variables: For the same reason that it has to use memory.
  • char, short, int - which is better?: Use int as much as possible because for 'char' and 'short' CPU has to do some shift operations before giving the value to the user
  • How to reduce the function call overhead?

  • Avoid using ++ and -- etc. within loop expressions. E.g.: while(n--){}, as this can sometimes be harder to optimize.
  • Minimize the use of global variables.
  • Declare anything within a file (external to functions) as static, unless it is intended to be global.
  • Use word-size variables if you can, as the machine can work with these better (instead of char, short, double, bit fields etc.).
  • Don't use recursion. Recursion can be very elegant and neat, but creates many more function calls which can become a large overhead.
  • Avoid the sqrt() square root function in loops - calculating square roots is very CPU intensive.
  • Single dimension arrays are faster than multi-dimension arrays.
  • Compilers can often optimize a whole file - avoid splitting off closely related functions into separate files, the compiler will do better if it can see both of them together (it might be able to inline the code, for example).
  • Single precision math may be faster than double precision - there is often a compiler switch for this.
  • Floating point multiplication is often faster than division - use val * 0.5 instead of val / 2.0.
  • Addition is quicker than multiplication - use val + val + val instead of val * 3. puts() is quicker than printf(), although less flexible.
  • Use #defined macros instead of commonly used tiny functions - sometimes the bulk of CPU usage can be tracked down to a small external function being called thousands of times in a tight loop. Replacing it with a macro to perform the same job will remove the overhead of all those function calls, and allow the compiler to be more aggressive in its optimization..
  • Binary/unformatted file access is faster than formatted access, as the machine does not have to convert between human-readable ASCII and machine-readable binary. If you don't actually need to read the data in a file yourself, consider making it a binary file.
  • If your library supports the mallopt() function (for controlling malloc), use it. The MAXFAST setting can make significant improvements to code that does a lot of malloc work. If a particular structure is created/destroyed many times a second, try setting the mallopt options to work best with that size.

Last, but definitely not least - turn compiler optimization on! Seems obvious, but is often forgotten in that last minute rush to get the product out on time. The compiler will be able to optimize at a much lower level than can be done in the source code, and perform optimizations specific to the target processor.

Sunday, April 4, 2021

Switches VS Routers

 Switches:

- Works out of the box straight away

- Supports broadcast

- Works on DL layer

- Creates a network

- Has more ports (typically, 24, 36, 48 ports etc).

- Works on MAC addresses (HW address)

- Maintains CAM table (Content Addressable Memory)

Routers:

- Does not work out of the box (needs configuration)

- Does not support broadcast

- Works on Network Layer

- Connects the networks

- Has limited set of ports (typically, 2, 4, 6, 8)

- Works on IP addresses (software address)

- Maintains Routing table

Tuesday, March 2, 2021

Friday, December 4, 2020

DOS Attack (Denial Of Service)

 https://www.cloudflare.com/learning/ddos/what-is-a-ddos-attack/

A distributed denial-of-service (DDoS) attack is a malicious attempt to disrupt the normal traffic of a targeted server, service or network by overwhelming the target or its surrounding infrastructure with a flood of Internet traffic


From a high level, a DDoS attack is like an unexpected traffic jam clogging up the highway, preventing regular traffic from arriving at its destination.


Thursday, November 5, 2020

Red Zone - Stack Frame (x86-64)

 https://devblogs.microsoft.com/oldnewthing/20190111-00/?p=100685

https://eli.thegreenplace.net/2011/09/06/stack-frame-layout-on-x86-64






Kernel Threads

  • kthreadd (pid = 2) created by kernel (pid = 0) during boot
  • kthreadd helps in creating other kernel threads which are required to run periodically/asynchronously
  • "ps" shows kernel threads
  • Everything under [square bracket] are kernel threads

sw0:FID128:root> ps -eaf
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 01:21 ?        00:00:00 init [5]
root         2     0  0 01:21 ?        00:00:00 [kthreadd]
root         3     2  0 01:21 ?        00:00:00 [ksoftirqd/0]
root         4     2  0 01:21 ?        00:00:00 [kworker/0:0]

  • All calls from user-space to create a new process (including "create_thread" in kthreadd), will end up in do_fork call which internally calls copy_process

Thursday, August 27, 2020

Thursday, May 28, 2020

CSS (Cascading Style Sheets)

https://classroom.udacity.com/courses/ud001/lessons/7473321627/concepts/74276264120923

CSS Tricks: https://css-tricks.com/almanac/

CSS: how the content should look in the webpage (layouts, colors etc)
HTML: the actual contents
[Without CSS, HTML allows basic formatting such as bold, italic etc, but nothing more. To use various layouts, use CSS]
NOTE: without CSS, browser also can apply default styling settings.
Youtube without CSS is something that would look like when the internet connection is slow.


  • CSS has rule-sets.
  • And a rule-set is nothing but rules on how to render the tags
  • For ex: div : {color: blue} => would mean, render everything under 'division' in body in blue color
  • Hence it has 2 parts: tags and the declarations. 
  • CSS rule-sets are written inside <style></style> tags inside <head> tags
  • Comments inside CSS is same as C or C++: /* CSS comments */
  • NOTE: Comments inside html is different <!-- comment here -->
  • attributes and classes:
    • p { colors: red }; => will change all the paragraph colors to red.
    • but if we want to change a particular paragraph (id) or a group of paragraphs (classes) to a color, we need id and classes.
    • while declaring a tag in <body> include the id (id is similar to a variable in C) or classes (group of tags marked to apply a particular setting)
    • <p id="site-description">check out my site description</p>
    • <p class="book-summary another-class">Algorithms</p>
      • NOTE: an html tag can belong to multiple classes (multiple groups/selectors)
    • And in CSS styles, 
      • <style>
        • .book-summary { => classes starts with '.'
          • colors:red
          • }
        • #site-description { => id (variables/attributes) starts with #
          • colors:pink;
          • }
  • Colors:
    • .sidebars {
      • color: rgb(0, 0, 225) => blue
      • color: blue => blue
      • color: #0000ff => blue
      • color: #00f => blue (short-hand representation of 0000ff)
  • Selectors:

HTML tags (trees)


  1. Each page should contain: head + body
  2. head elements are not displayed; mainly used for title, references, meta-data, CSS-styles etc
  3. Body elements are displayed.
  4. Each page should have only one body
  5. Inside body we can have: divisions, header strings, links, images, buttons, paragraphs, sub-strings, super-strings, spans etc.
  • divisions: <div></div>: Inside divisions, you can organize header strings, buttons etc. A body can have multiple divisions
  • header strings: <h1-6> </h1-6>: h1 is the highest
  • links: <a href="https://www.gmail.com">GMAIL</a>: a means anchor here
  • images: <img src="https://page-containing-image" alt="some description"> [NOTE: images are similar to links: instead of href, we have src. But images dont have end tags </img>; hence, they are one of type called "void elements"
  • <figure>and <figcaption>=> can be used along with image to provide figure section
  • For ex: 
    • <figure>
    • <img src="local_file.jpg" alt="description">
    • <figurecaption>Caption for the image which will be displayed below the image</figurecaption>
    • </figure>
  • <em></em> => for italic
  • <strong></strong> => for bold
  • <ul><li>option1</li><li>option2</li></ul> => unordered list
  • <ol> with numbers by default
  • Comments inside html: <!-- comment here -->
  • NOTE: Comments inside CSS is same as C: /* CSS comment */
  1. sdf

Monday, October 7, 2019

Fetching Price of a product online

import requests
from bs4 import BeautifulSoup
import smtplib
import getpass

def get_price():
    ''' the url from which u need the product details '''
    URL = 'https://www.amazon.in/JBL-Splash-Proof-Portable-Wireless-Bluetooth/dp/B0125QA4IO?ref_=Oct_DLandingS_PC_a25847b7_13'
    ''' user-agent involved: search for 'my user agent' in your browser to get this info '''
    headers = {'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'}

    ''' get the whole page; if u print 'page' it will be nasty and big '''
    page = requests.get(URL, headers = headers)

    ''' parse the page (using html parser) '''
    soup = BeautifulSoup(page.content, 'html.parser')

    ''' find the id (aka variable) used in browser that holds product info '''
    product = soup.find(id = 'productTitle').get_text().strip()

    ''' similarly get the price '''
    price = soup.find(id = 'priceblock_ourprice').get_text().strip()
    print (product)
    print (price)

    ''' some manipulation needed to get the price in value (instead of string) '''
    converted_price = price.strip('₹').strip()
    converted_price = float(converted_price.replace(',', ''))
    print (converted_price)
    return converted_price

def send_mail(mailid, password, current_price):
    ''' get the SMTP object '''
    server = smtplib.SMTP('smtp.gmail.com', 587)

    ''' extended hello '''
    server.ehlo()

    ''' put the smtp connection in tls mode; this to get encrypted connection '''
    server.starttls()
    server.ehlo()

    ''' login using your credentials '''
    server.login(mailid, password)

    #subject = 'Hey, the price fell down to ₹ {}/-'.format(current_price).encode('utf-8')
    #subject = 'Hey, the price fell down to ₹ %s' % (str(current_price)).encode('utf-8')
    subject = 'Hey, the price fell down'
    body = 'Check the amazon link for more details: https://www.amazon.in/JBL-Splash-Proof-Portable-Wireless-Bluetooth/dp/B0125QA4IO?ref_=Oct_DLandingS_PC_a25847b7_13'    msg = f"Subject: {subject}\n\n{body}"    server.sendmail('hkumar.sekar@gmail.com', 'harish.sekar@broadcom.com', msg)

    ''' don't forget to delete the smtp object aka. close connection '''
    server.quit()

    print ("Hey, the price dropped. Mail is sent")

def main():
    mailid = input('Enter your email ID: ')
    p = getpass.getpass()
    current_price = get_price()

    if current_price < 6000:
        send_mail(mailid, p, current_price)

if __name__ == '__main__':
    main()

PROGRAM OUTPUT:
C:\Users\hs411053\PycharmProjects\scraper\venv\Scripts\python.exe C:/Users/hs411053/PycharmProjects/scraper/scraper
Enter your email ID: hkumar.sekar@gmail.com
Password:
JBL Flip 3 Portable Wireless Speaker with Powerful Sound & Mic (Blue)
₹ 5,599.00
5599.0
Hey, the price dropped. Mail is sent

Process finished with exit code 0
And the Mail would have been sent.

Sunday, October 6, 2019

How to Print in Makefile

Source: https://stackoverflow.com/questions/11775733/how-can-i-print-message-in-makefile/11776179


 15 # for TRACEGEN
 16 include $(MAKEDIR)/Tools.make
 17
 18 ifeq ($(CONFIG_SOMETHING),y)
 19 EXTRA_CFLAGS += -fsanitize=kernel-address
 20 $(info ************  TEST VERSION ************)
 21 else
 22 $(info ************  ELSE VERSION ************)
 23 endif

$(info your_text) : Information. This doesn't stop the execution.
$(warning your_text) : Warning. This shows the text as a warning.
$(error your_text) : Fatal Error. This will stop the execution.

To print a variable in Makefile:

 18 $(info $$CONFIG_VAR1 is [${CONFIG_VAR1}])
 19 $(info $$CONFIG_VAR2 is [${CONFIG_VAR2}])


Tuesday, October 1, 2019

What is the smallest integer greater than 95555 in which there will be 4 identical numbers?

Ans: 96666? nope, its 95999 :-)


Saturday, August 31, 2019

Direct Memory Access (DMA)

Reference:

If IO device (such as disk controller) needs data to be written or read from the memory, it used to to through the CPU like below.


In the above image, if IO can talk to/access memory directly, the number of cycles will reduce drastically. To achieve this direct memory access by an IO device, a special called DMA controller is needed.

Now, there are 4 components involved in DMA theory. Picture below.

YOUTUBE LINK: https://www.youtube.com/watch?v=Xkpu8BXi3aI









Here is how it works:
1. 

Monday, May 13, 2019

Bubble Sort

Pseudocode:


for j = 0 to n -2 // no need till n-2 as it will validate already properly aligned values(see code)
    if a[j] > a[j+1]
        swap (a[j], a[j+1])
 After the above pass, the largest element will come at the end.

Perform the above pass for each of the elements in the array.

Code
#include <stdio.h>

#define NELEMS(x) (sizeof (x) / sizeof (x[0]))

void display(int arr[], int n)
{
    int i;
    for (i = 0; i < n; ++i)
        printf("%d ", arr[i]);

    printf("\n");
}

void swap(int *x, int *y)
{
    int t = *x;
    *x = *y;
    *y = t;
}

void bubble(int arr[], int n)
{
    int i, j;
    int swapped = 0;
    for (i = 0; i < n - 1; ++i) { // no need of <n as bigger will find its way anyway
        swapped = 0;
        for (j = 0; j < n - i - 1; ++j) { // j < n-2 also works, but this is not needed
            if (arr[j] > arr[j + 1]) {
                swap(arr + j, arr + j + 1);
                swapped = 1;
                display(arr, 8);
            }
        }
        if (swapped == 0) break; // if no swap happened, no need to continue any further
    }
}

int main()
{
    int arr[] = { 17, 21, 19, 15, 5, 99, 1, 0 };
    /* int arr[] = { 17, 21, 19, 98, 99, 100, 101, 102 }; // almost sorted (usage of swapped flag helps here) */

    printf("Unsorted: ");
    display(arr, NELEMS(arr));

    bubble(arr, NELEMS(arr));

    printf("Sorted: ");
    display(arr, NELEMS(arr));
}

Output:
Unsorted: 17 21 19 15 5 99 1 0
17 19 21 15 5 99 1 0
17 19 15 21 5 99 1 0
17 19 15 5 21 99 1 0
17 19 15 5 21 1 99 0
17 19 15 5 21 1 0 99
17 15 19 5 21 1 0 99
17 15 5 19 21 1 0 99
17 15 5 19 1 21 0 99
17 15 5 19 1 0 21 99
15 17 5 19 1 0 21 99
15 5 17 19 1 0 21 99
15 5 17 1 19 0 21 99
15 5 17 1 0 19 21 99
5 15 17 1 0 19 21 99
5 15 1 17 0 19 21 99
5 15 1 0 17 19 21 99
5 1 15 0 17 19 21 99
5 1 0 15 17 19 21 99
1 5 0 15 17 19 21 99
1 0 5 15 17 19 21 99
0 1 5 15 17 19 21 99
Sorted: 0 1 5 15 17 19 21 99

Time Complexity: O(n^n)