42

4

I use curly braces with all of my switch case statements in C/Objective-C/C++

I had not, until a few moments ago, considered whether including the break; statement inside the braces was good or bad practice. I suspect that it doesn't matter, but I figure it is still worth asking.

 

 

 

 

 

Just a give a slightly more detailed answer...

The official C99 specification says the following about the break statement:

A break statement terminates execution of the smallest enclosing switch or iteration statement.

So it really doesn't matter. As for me, I put the break inside the curly braces. Since you can also have breaks in other places inside your curly braces, it's more logical to also have the ending break inside the braces. Kind of like the return statement.

 

 

 

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

In this blog post, we will see the C program to convert Hexadecimal to Decimal. In the interview, people ask the below questions,

 

  • How will you convert hexadecimal to decimal value?
  • Write a C program to convert hexadecimal number system value to decimal number system?
  • Implement logic to convert a hexadecimal number to a decimal number system?
  • Get a hexadecimal number from the user and convert it to its decimal equivalent?

Examples:

Input : 67

Output : 103

 

Input : 512

Output : 1298

 

Input: 123

Output: 291

 

We need to know the decimal and hexadecimal numbers before writing the C program to convert hexadecimal to the decimal.

The hexadecimal number system is a base 16 number system. The hexadecimal number is represented by 16 values i.e 0 1 2 3 4 5 6 7 8 9 A B C D E F.

The decimal number system is a base 10 number system. It uses 10 symbols to represent all numbers i.e. 0123456789

 

Logic to convert Hexadecimal to Decimal System:

We know that in hexadecimal number uses 16 symbols {0, 1, 2, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F} to represent all numbers. Here, (A, B, C, D, E, F) represents (10, 11, 12, 13, 14, 15).

We need to run a loop from 0 to  (buffer_length -1). The buffer_length  is the length of the buffer which contains entered hexadecimal number.

To convert hex to decimal, we need to extract the digits of a given hexadecimal number from the buffer. At the time of extracting digits from the hexadecimal number, multiply the digit with the proper base (Power of 16) and add it to the variable “decimal”.

 

After ending the iteration, the variable “decimal” will store the resultant decimal number.

For Example:
If the hexadecimal number is 1A.
decimal = 1*(16^1) + 10*(16^0) = 26

Below diagram explains how to convert hexadecimal number ( 1AB ) to equivalent decimal value:

 

C Program to convert hexadecimal to decimal number system:

 

 

 

#include <stdio.h>
#include <math.h>
#include <string.h>
#define ARRAY_SIZE  20
int main()
{
    char hex[ARRAY_SIZE];
    long long decimal = 0, base = 1;
    int i = 0, value, length;
    /* Get hexadecimal value from user */
    printf("Enter hexadecimal number: ");
    fflush(stdin);
    fgets(hex,ARRAY_SIZE,stdin);
    length = strlen(hex);
    for(i = length--; i >= 0; i--)
    {
        if(hex[i] >= '0' && hex[i] <= '9')
        {
            decimal += (hex[i] - 48) * base;
            base *= 16;
        }
        else if(hex[i] >= 'A' && hex[i] <= 'F')
        {
            decimal += (hex[i] - 55) * base;
            base *= 16;
        }
        else if(hex[i] >= 'a' && hex[i] <= 'f')
        {
            decimal += (hex[i] - 87) * base;
            base *= 16;
        }
    }
    printf("\nHexadecimal number = %s", hex);
    printf("Decimal number = %lld\n", decimal);
    return 0;
}

 

 

 

Enter hexadecimal number: 1A
Hexadecimal number = 1A
Decimal number = 26
블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

First, explain that the delay function of the first atomic brother is no problem. Atomic brother's delay function is used in STM32F103, depending on the type of development board. Here are the delay functions of STM32F103 and STM32F030.

(1) Used in STM32F030:

#include "stm32f0xx.h"
#include "delay.h"
//////////////////////////////////////////////////////////////////////////////////	 
//This program is for learning use only and cannot be used for any other purpose without permission from the author
 //Mini STM32 development board
 //Use SysTick's normal counting mode to manage the delay
 //Including delay_us, delay_ms
 //Punctual atom @ALIENTEK
 //Technical Forum: www.openedv.com
 //Date of modification: 2010/5/27
 //Version: V1.2
 //Copyright, piracy will be investigated.
 //Copyright(C) punctual atom 2009-2019
//All rights reserved
//********************************************************************************
 //V1.2 modification instructions
 //Fixed the error that the call in the interrupt occurs in an infinite loop
 //To prevent inaccurate delay, use do while structure!
//////////////////////////////////////////////////////////////////////////////////	 
 static u8 fac_us=0;//us delay multiplier
 static u16 fac_ms=0;//ms delay multiplier
 //Initialize delay function
 //The clock of SYSTICK is fixed at 1/8 of the HCLK clock
 //SYSCLK: system clock
void delay_init(u8 SYSCLK)
{
	 SysTick->CTRL&=0xfffffffb;//bit2 clear, select external clock HCLK/8
	fac_us=SYSCLK/8;		    
	fac_ms=(u16)fac_us*1000;
}								    
 //Delay nms
 //Note the range of nms
 //SysTick->LOAD is a 24-bit register, so the maximum delay is:
//nms<=0xffffff*8*1000/SYSCLK
 //SYSCLK unit is Hz, nms unit is ms
 //For 72M, nms<=1864 
void delay_ms(u16 nms)
{	 		  	  
	u32 temp;		   
	 SysTick->LOAD=(u32)nms*fac_ms;//Time loading (SysTick->LOAD is 24bit)
	 SysTick->VAL =0x00; //Clear counter
	 SysTick->CTRL=0x01; //Start countdown  
	do
	{
		temp=SysTick->CTRL;
	}
	 while(temp&0x01&&!(temp&(1<<16)));//Wait time to arrive   
	 SysTick->CTRL=0x00; //Turn off the counter
	 SysTick->VAL =0X00; //Clear counter	  	    
}   
 //Delay nus
 //nus is the number of us to be delayed.		    								   
void delay_us(u32 nus)
{		
	u32 temp;	    	 
	 SysTick->LOAD=nus*fac_us; //Time to load	  		 
	 SysTick->VAL=0x00; //Clear counter
	 SysTick->CTRL=0x01; //Start countdown 	 
	do
	{
		temp=SysTick->CTRL;
	}
	 while(temp&0x01&&!(temp&(1<<16)));//Wait time to arrive   
	 SysTick->CTRL=0x00; //Turn off the counter
	 SysTick->VAL =0X00; //Clear counter	 
}

 

(2) Used in STM32F103:

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요

차례1.1. 사용법1.2. 설명1.3. 반환값1.4. 에러1.5. 예제1.6. 참고문헌

현재 시간을 가져오고 시스템의 시간값을 설정한다.


1.1. 사용법

#include <sys/time.h>
#include <unistd.h>

int gettimeofday(struct timeval *tv, struct timezone *tz);
int settimeofday(const struct timeval *tv ,  const  struct
             timezone *tz);

 

1.2. 설명

gettimeofday()은 time(2)와 매우 비슷하지만 마이크로초 단위의 시간 까지 되돌려준다. 현재는 time(2)를 대신해서 쓰이고 있으며, 가능한 time(2)대신 이 함수를 사용하는 걸 권장한다.

첫번째 인자인 tv는 현재 시스템 시간을 저장하기 위한 구조체로 다음과 같이 정의되어 있다.

struct timeval
{
    long tv_sec;       // 초
    long tv_usec;      // 마이크로초
}

두번째 인자인 tz은 타임존을 설정하기 위해서 사용된다.

struct timezone
{
    int tz_minuteswest:  // 그리니치 서측분차  
    int tz_dsttime       // DST 보정타입(일광 절약시간)
}
	

현재 timezone 구조체는 사용되지 않고 있으며, 앞으로도 지원되지 않을 것이다. 간혹 커널 소스등에서 이 필드가 사용되는 경우가 있는데, 모든 경우에 버그로 판단되어서 무시한다. 복잡하게 생각할 필요 없이 tz은 NULL을 사용하도록 한다.

1.3. 반환값

성공하면 0 실패하면 -1을 리턴한다.

1.4. 에러

EFAULT

tv나 tz이 접근할 수 없는 영역을 가리키고 있다.

1.5. 예제

#include <sys/time.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>

int main()
{
    struct timeval mytime;

    // 현재 시간을 얻어온다.
    gettimeofday(&mytime, NULL);
    printf("%ld:%ld\n", mytime.tv_sec, mytime.tv_usec);

    // 시간을 1시간 뒤로 되돌려서 설정한다.
    mytime.tv_sec -= 3600;
    settimeofday(&mytime, NULL);
    return 0;
}


1.6. 참고문헌


  1. Unix 시간 다루기

  2.  
  3. time(2)

  4. stime(2)

 

참고 :

블로그 이미지

remoted

Remoted's IT LAB & POST DATABASE

댓글을 달아 주세요