Vous êtes sur la page 1sur 41

Contents

1. Learn C in a Minutes ........................................................................................................................ 2 2. Relational Operators, Logical Operators, If, Else, Else If, Conditional Operator, Bits, Bytes, Looping ..................................................................................................................................................... 5 3. Switch, Strings, Arrays and more.................................................................................................... 8 4. Pointers, Arrays and Functions ..................................................................................................... 12 5. All About Structs ............................................................................................................................. 15 6. Structs, Unions, Enums, Linked Lists and Recursice Structures............................................... 18 7. Messing with Strings, Chars, Booleans, Functions & Pointers .................................................. 21 8. How to Dynamically Allocate Memory with malloc() ................................................................. 22 9. Working with Struct Linked Lists ................................................................................................. 25 10. 11. 12. 13. 14. Working with Struct Linked Lists (2) ........................................................................................ 27 Text I/O File .................................................................................................................................. 30 Binary File I/O & Error Handling with C ................................................................................. 32 Converting from Base 10 to Base 2, 8 and 16 ............................................................................ 34 Convert from Others Base to Base 10 ........................................................................................ 36

15. Passing Memory Addresses, Bitwise Operators, Signed Integers, Shift Operators, Twos Compliment, Bit Masking ..................................................................................................................... 38

1. Learn C in a Minutes Tutorial_1


#include <stdio.h> #include <stdlib.h> #include <string.h> #define MYNAME "Hoang Nhu Vinh" int globalVar = 100; int main() { char firstLetter = 'V'; int age = 23; long int superBigNum = -1231231; float piValue = 3.14159; double reallyBigPi = 3.14159159159159; printf("\n"); printf("This will print to screen\n\n"); printf("I am %d years old\n\n", age); printf("Big number is %ld \n\n", superBigNum); printf("Pi = %.5f\n\n", piValue); printf("Big Pi = %.10f\n\n", superBigNum); printf("The first letter in my name is %c\n\n", firstLetter); printf("My name is %s\n\n","Vinh"); char myName[]= "Nhu Vinh"; printf("My name is %s\n\n", myName); strcpy(myName,"Cam Trinh"); printf("My name is %s\n\n", myName); return 0; }

Tutorial_1_2
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MYNAME "Hoang Nhu Vinh" int globalVar = 100; int main() { char middleInitial; printf("What is your middle initial?\n\n"); scanf("%c",&middleInitial); printf("Middle initial is %c\n\n", middleInitial); char firstName[30], lastName[30]; printf("What is your first name\n"); scanf("%s",firstName); printf("What is your last name\n"); scanf("%s",lastName); //printf("Your name is %s &c %s \n\n",firstName,middleInitial,lastName); int month,day,year; printf("What's your birth date?\n"); scanf("%d%d%d", &month,&day,&year); return 0; }

2. Relational Operators, Logical Operators, If, Else, Else If, Conditional Operator, Bits, Bytes, Looping Tutorial_2
#include <stdio.h> void main(){ printf("\n"); int num1 = 1, num2 = 2; printf("Is 1 > 2 : %d\n\n",num1 > num2); if(num1 > num2){ printf("%d is greater then %d\n\n", num1, num2); } else if(num1 < num2){ printf("%d is less then %d\n\n", num1, num2); } else { printf("%d is equal to %d\n\n", num1, num2); } int custAge = 38; if(custAge > 21 && custAge < 35) printf("They are welcome\n\n"); else printf("They are not welcome\n\n"); printf("! turns a true into false : %d\n\n", !1); int bobMissedDays = 8, bobTotalSales = 24000, bobNewCust = 32; if(bobMissedDays < 10 && bobTotalSales > 30000 || bobNewCust > 30){ printf("Bob gets a raise\n\n"); } else { printf("Bob doesn't get a raise\n\n"); } char* legalAge = (custAge > 21) ? "true" : "false"; printf("Is the customer of legal age? %s\n\n", legalAge); int numOfProducts = 10; printf("I bought %s products\n\n", (numOfProducts > 1) ? "many" : "one"); printf("A char takes up %d bytes\n\n", sizeof(char)); printf("An int takes up %d bytes\n\n", sizeof(int)); printf("A long int takes up %d bytes\n\n", sizeof(long int)); printf("A float takes up %d bytes\n\n", sizeof(float)); printf("A double takes up %d bytes\n\n", sizeof(double)); int bigInt = 2147483648; printf("I'm bigger then you may have heard %d\n\n", bigInt); int numberHowBig = 0; printf("How Many Bits? "); scanf(" %d", &numberHowBig); printf("\n\n"); int myIncrementor = 1, myMultiplier = 1, finalValue = 1; while(myIncrementor < numberHowBig){ myMultiplier *= 2; finalValue = finalValue + myMultiplier; printf("finalValue: %d myMultiplier: %d myIncrementor: %d\n\n", finalValue, myMultiplier, myIncrementor); myIncrementor++; } if ((numberHowBig == 0) || (numberHowBig == 1)){

printf("Top Value: %d\n\n", numberHowBig); } else { printf("Top Value: %d\n\n", finalValue); } int secretNumber = 10, numberGuessed = 0; while(1){ printf("Guess My Secret Number: "); scanf(" %d", &numberGuessed); if(numberGuessed == 10){ printf("You Got It"); break; } } printf("\n\n"); char sizeOfShirt; do { printf("What Size of Shirt (S,M,L): "); scanf(" %c", &sizeOfShirt); } while(sizeOfShirt != 'S' && sizeOfShirt != 'M' && sizeOfShirt != 'L'); for(int counter = 0; counter <= 20; counter++){ printf("%d ", counter); } printf("\n\n"); for(int counter = 0; counter <= 40; counter++){ if((counter % 2) == 0) continue; printf("%d ", counter); } }

3. Switch, Strings, Arrays and more Tutorial_3


#include <stdio.h> // Needed for exit() #include <stdlib.h> void main(){ int whatToDo = 0; do{ printf("\n"); printf("1. What Time is It?\n"); printf("2. What is Todays Date?\n"); printf("3. What Day is It?\n"); printf("4. Quit\n"); scanf(" %d", &whatToDo); } while(whatToDo < 1 || whatToDo > 4); // How to handle the input with if if(whatToDo == 1){ printf("Print the time\n"); } else if(whatToDo == 2){ printf("Print the date\n"); } else if(whatToDo == 3){ printf("Print the day\n"); } else { printf("Bye Bye\n"); exit(0); } printf("\n"); switch(whatToDo){ case(1) : printf("Print the time\n"); break; case(2) : printf("Print the date\n"); break; case(3) : printf("Print the day\n"); break; default : printf("Bye Bye\n"); exit(0); break; } }

Tutorial_3_2
#include <stdio.h> #include <string.h> int void main(){ printf("\n"); char wholeName[12] = "Derek Banas"; int primeNums[3] = {2, 3, 5,}; int morePrimes[] = {13, 17, 19, 23}; printf("The first prime in the list is %d\n\n", primeNums[0]); char city[7] = {'C', 'h', 'i', 'c', 'a', 'g', 'o'}; char anotherCity[5] = {'E', 't', 'n', 'a', '\0'}; printf("A City %s\n\n", anotherCity); char thirdCity[] = "Paris"; char yourCity[30]; printf("What city do you live in? "); fgets(yourCity, 30, stdin); printf("Hello %s\n\n", yourCity); int i1; for(i1 = 0; i1 < 30; i1++){ if(yourCity[i1] == '\n'){ yourCity[i1] = '\0'; break; } } printf("Hello %s\n\n", yourCity); printf("Is your city Paris? %d\n\n", strcmp(yourCity, thirdCity));

char yourState[] = ", Pennsylvania"; strcat(yourCity, yourState); printf("You live in %s\n\n", yourCity); printf("Letters in Paris : %d\n\n", strlen(thirdCity)); strcpy(yourCity, "El Pueblo del la Reina de Los Angeles"); printf("The new name is %s\n\n", yourCity); }

Tutorial_3_3
#include <stdio.h> // Needed for exit(), rand() #include <stdlib.h> int globalVar = 0; int addTwoInts(int num1, int num2){ return num1 + num2; } void changeVariables(){ int age = 40; printf("age inside of function = %d\n\n", age); globalVar = 100; printf("globalVar inside of function = %d\n\n", globalVar); } void main(){ int total = addTwoInts(4,5); printf("The Sum is %d\n\n", total); int age = 10; globalVar = 50; printf("age before a call to the function = %d\n\n", age); printf("globalVar before a call to the function = %d\n\n", globalVar);

10

changeVariables(); printf("age after a call to the function = %d\n\n", age); printf("globalVar after a call to the function = %d\n\n", globalVar); }

11

4. Pointers, Arrays and Functions Tutorial_4


#include <stdio.h> void main(){ int rand1 = 12, rand2 = 15; printf("rand1 = %p : rand2 = %p\n\n", &rand1, &rand2); printf("Size of int %d\n\n", sizeof(int)); int * pRand1 = &rand1; printf("Pointer %p\n\n", pRand1); printf("Value %d\n\n", pRand1); printf("Value %d\n\n", *pRand1); int primeNumbers[] = {2,3,5,7}; printf("First index : %d\n\n", primeNumbers[0]); printf("First index with * : %d\n\n", *primeNumbers); printf("Second index with * : %d\n\n", *(primeNumbers + 1)); char * students[4] = {"Sally", "Mark", "Paul", "Sue"}; for(int i = 0; i < 4; i++){ printf("%s : %d\n\n", students[i], &students[i]); } }

12

Tutorial_4_2
#include <stdio.h> #include <stdlib.h> void generateTwoRandomNums(int rand1, int rand2){ rand1 = rand() % 50 + 1; rand2 = rand() % 50 + 1; printf("New rand1 in function = %d\n\n", rand1); printf("New rand2 in function = %d\n\n", rand2); } void pointerRandomNumbers(int* rand1, int* rand2){ *rand1 = rand() % 50 + 1; *rand2 = rand() % 50 + 1; printf("New rand1 in pointer function = %d\n\n", *rand1); printf("New rand2 in pointer function = %d\n\n", *rand2); } void editMessageSent(char* message, int size){ char newMessage[] = "New Message"; if(size > sizeof(newMessage)){ int i ; for(i = 0; i < sizeof(newMessage); i++){ message[i] = newMessage[i]; } } else { printf("New Message is to big\n\n"); } } void main(){ int rand1 = 0, rand2 = 0; generateTwoRandomNums(rand1, rand2); printf("rand1 = %d\n\n", rand1); printf("rand2 = %d\n\n", rand2); rand1 = 0, rand2 = 0; printf("Main Before Function Call\n\n"); printf("rand1 = %d : rand2 = %d\n\n", rand1, rand2); pointerRandomNumbers(&rand1, &rand2); printf("Main After Function Call\n\n"); printf("rand1 = %d : rand2 = %d\n\n", rand1, rand2); char randomMessage[] = "Edit my function"; printf("Old Message: %s \n\n", randomMessage); editMessageSent(randomMessage, sizeof(randomMessage)); printf("New Message: %s \n\n", randomMessage); }

13

14

5. All About Structs Tutorial_5


#include <stdio.h> #include <stdlib.h> struct dog { const char *name; const char *breed; int avgHeightCm; int avgWeightLbs; }; void getDogInfo(struct dog theDog) { printf("Name:%s\n\n", theDog.name); printf("Breed:%s\n\n", theDog.breed); printf("Hieght:%d\n\n", theDog.avgHeightCm); printf("Weight:%d\n\n", theDog.avgWeightLbs); } void getMemoryLocations(struct dog theDog) { printf("Name location:%d\n\n", theDog.name); printf("Breed location:%d\n\n", theDog.breed); printf("Height location:%d\n\n", &theDog.avgHeightCm); printf("Name location:%d\n\n", &theDog.avgWeightLbs); } int main() { struct dog cujo = {"Cujo","Saint",90,150}; getDogInfo(cujo); struct dog cujo2 = cujo; getMemoryLocations(cujo); getMemoryLocations(cujo2); return 0; }

15

Tutorial_5_2
#include <stdio.h> #include <stdlib.h> struct dogsFavs { char *food; char *friends; }; typedef struct dog { const char *name; const char *breed; int avgHeightCm; int avgWeightLbs; struct dogsFavs favoriteThings; } dog; void getDogsFavs(dog theDog) { printf("\n"); printf("%s loves %s and his friend is %s\n", theDog.name,theDog.favoriteThings.food,theDog.favoriteThings.friends); } void setDogWeightPtr(dog *theDog, int newWeight) { theDog->avgWeightLbs = newWeight; printf("New weight is : %d\n\n", theDog->avgWeightLbs);

16

} int main() { dog benji = {"Benji","Silky",90,180,{"Meat","Joe Camp"}}; getDogsFavs(benji); setDogWeightPtr(&benji,60); printf("Wieght in the main is: %d", benji.avgWeightLbs); return 0; }

17

6. Structs, Unions, Enums, Linked Lists and Recursice Structures Tutorial_6


#include <stdio.h> int main(){ typedef union{ short individual; float pound; float ounce; } amount; amount orangeAmt = {.ounce = 16}; orangeAmt.individual = 4; printf("Orange Juice Amount: %.2f : Size: %d\n\n", orangeAmt.ounce, sizeof(orangeAmt.ounce)); printf("Number of Oranges: %d : Size: %d\n\n", orangeAmt.individual, sizeof(orangeAmt.individual)); printf("Indiv Location: %d\n\n", &orangeAmt.individual); orangeAmt.pound = 1.5; printf("Pounds of Oranges: %.2f : Size: %d\n\n", orangeAmt.pound, sizeof(orangeAmt.pound)); printf("Pound Location: %d\n\n", &orangeAmt.individual); typedef struct{ char *brand; amount theAmount; } orangeProduct; orangeProduct productOrdered = {"Chiquita", .theAmount.ounce = 16}; printf("You bought %.2f ounces of %s oranges\n\n", productOrdered.theAmount.ounce, productOrdered.brand); typedef enum{ INDIV, OUNCE, POUND } quantity; quantity quantityType = INDIV; orangeAmt.individual = 4; if(quantityType == INDIV){ printf("You bought %d oranges\n\n", orangeAmt.individual); } else if(quantityType == OUNCE){ printf("You bought %.2f ounces of oranges\n\n", orangeAmt.ounce); } else { printf("You bought %.2f pounds of oranges\n\n", orangeAmt.pound); } }

18

Tutorial_6_2
#include <stdio.h> #include <stdlib.h> typedef struct product { const char *name; float price; struct product *next; } product; void printLinkedList(product *pProduct) { while (pProduct != NULL) { printf("A %s costs %.2f\n\n", pProduct->name, pProduct->price); pProduct = pProduct->next; } } int main() { product product product product

tomato = {"Tomato", .51, NULL}; potato = {"Potato", .21, NULL}; lemon = {"Lemon", .34, NULL}; milk = {"Milk", 3.51, NULL};

19

product turkey = {"Turkey", 1.51, NULL}; tomato.next = &potato; potato.next = &lemon; lemon.next = &milk; milk.next = &turkey; product apple = {"Apple",1.58, NULL}; lemon.next = &apple; apple.next = &milk; printLinkedList(&tomato); return 0; }

20

7. Messing with Strings, Chars, Booleans, Functions & Pointers Tutorial_7_2


#include #include #include #include #include <stdio.h> <stdlib.h> <stdbool.h> <string.h> <ctype.h>

int main() { bool isANumber; int number; int sumOfNumbers = 0; printf("Enter a number: "); isANumber = (scanf("%d", &number) == 1); while(isANumber) { sumOfNumbers = sumOfNumbers +number; printf("Enter a number: "); isANumber = (scanf("%d", &number) == 1); } printf("The Sum is %d\n\n", sumOfNumbers); return 0; }

21

8. How to Dynamically Allocate Memory with malloc() Tutorial_8


#include <stdio.h> #include <stdlib.h> int main() { int amtOfNumbersToStore; printf("How many numbers do you want to store ?"); scanf("%d", &amtOfNumbersToStore); int *pRandomNumbers; pRandomNumbers = (int *) malloc(amtOfNumbersToStore *sizeof(int)); if(pRandomNumbers != NULL) { int i = 0; printf("Enter a Number or Quit: "); while(i < amtOfNumbersToStore &&scanf("%d",&pRandomNumbers[i]) == 1) { printf("Enter a number or Quit: "); i++; } printf("\nYou entered the following numbers\n"); int j; for (j = 0; j < i; j++) { printf("%d\n", pRandomNumbers[j]); } } free(pRandomNumbers); return 0; }

22

Tutorial_8_2
#include <stdio.h> #include <stdlib.h> struct product { float price; char productName[30]; }; int main() { struct product *pProducts; int i,j; int numberOfProducts; printf("Enter the Number of Products to Store"); scanf("%d", &numberOfProducts); pProducts = (struct product *) malloc(numberOfProducts * sizeof(struct product)); for (i = 0; i < numberOfProducts; ++i) { printf("Enter a Product Name:"); scanf("%s", &(pProducts+i)->productName); printf("Enter a Product Price:"); scanf("%f", &(pProducts+i)->price); } printf("Products Stored\n"); for (j = 0; j < numberOfProducts; ++j) { printf("%s\t%.2f\n", (pProducts+j)->productName, (pProducts+j)->price); } free(pProducts); return 0; }

23

24

9. Working with Struct Linked Lists Tutorial_9


#include <stdio.h> #include <stdlib.h> #include <string.h> struct product { float price; char productName[30]; struct product *next; }; struct product *pFirstNode = NULL; struct product *pLastNode = NULL; void createNewList(){ struct product *pNewStruct = (struct product *) malloc(sizeof(struct product)); pNewStruct->next = NULL; printf("Enter Product Name"); scanf("%s", &(pNewStruct)->productName); printf("Enter Product Price"); scanf("%f", &(pNewStruct)->price); pFirstNode = pLastNode = pNewStruct; } void inputData() { if (pFirstNode == NULL) { createNewList(); }else { struct product *pNewStruct = (struct product *) malloc(sizeof(struct product)); printf("Enter Product Name"); scanf("%s", &(pNewStruct)->productName); printf("Enter Product Price"); scanf("%f", &(pNewStruct)->price); if (pFirstNode == pLastNode) { pFirstNode->next = pNewStruct; pLastNode = pNewStruct; pNewStruct->next = NULL; } else { pLastNode->next = pNewStruct; pNewStruct->next = NULL; pLastNode = pNewStruct; } } } void outputData()

25

{ struct product *pProducts = pFirstNode; printf("Products entered \n\n"); while (pProducts != NULL) { printf("%s costs %.2f\n\n",pProducts->productName,pProducts->price); pProducts = pProducts->next; } } int main() { inputData(); inputData(); inputData(); outputData(); return 0; }

26

10.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct product { float price; char productName[30]; struct product *next;

Working with Struct Linked Lists (2) Tutorial_10

}; struct product *pFirstNode = NULL; struct product *pLastNode = NULL; void createNewList(){ struct product *pNewStruct = (struct product *) malloc(sizeof(struct product)); pNewStruct->next = NULL; printf("Enter Product Name"); scanf("%s", &(pNewStruct)->productName); printf("Enter Product Price"); scanf("%f", &(pNewStruct)->price); pFirstNode = pLastNode = pNewStruct; } void inputData() { if (pFirstNode == NULL) { createNewList(); }else { struct product *pNewStruct = (struct product *) malloc(sizeof(struct product)); printf("Enter Product Name"); scanf("%s", &(pNewStruct)->productName); printf("Enter Product Price"); scanf("%f", &(pNewStruct)->price); if (pFirstNode == pLastNode) { pFirstNode->next = pNewStruct; pLastNode = pNewStruct; pNewStruct->next = NULL; } else { pLastNode->next = pNewStruct; pNewStruct->next = NULL; pLastNode = pNewStruct; }

27

} } void outputData() { struct product *pProducts = pFirstNode; printf("Products entered \n\n"); while (pProducts != NULL) { printf("%s costs %.2f\n\n",pProducts->productName,pProducts->price); pProducts = pProducts->next; } } struct product *pProductBeforeProductToDelete = NULL; struct product* searchForProduct(char * productName) { struct product *pProductIterator = pFirstNode; while(pProductIterator != NULL) { int areTheyEqual = strncmp(pProductIterator->productName,productName, 30); if(!areTheyEqual) { printf("%s was found and it costs %.2f\n\n",pProductIterator>productName,pProductIterator->price); return pProductIterator; } pProductIterator = pProductIterator->next; pProductBeforeProductToDelete = pProductIterator; } printf("%s was not found", productName); return NULL; } void removeProduct(char * productName) { struct product *pProductToDelete = NULL; pProductToDelete = searchForProduct(productName); if(pProductToDelete != NULL) { printf("%s was deleted", productName); if (pProductToDelete == pFirstNode) { pFirstNode = pProductToDelete->next; }else { pProductBeforeProductToDelete->next = pProductToDelete->next; } } } int main() { inputData(); inputData(); inputData();

28

outputData(); removeProduct("Tomato"); outputData(); return 0; }

29

11.

Text I/O File Tutorial_11

#include <stdio.h> #include <stdlib.h> int main() { int randomNumber; FILE *pFile; pFile = fopen("randomnumbers.txt", "w"); if (!pFile) { printf("Error: could not write to File"); return 1; } int i; for (i = 0 ; i < 10; i++) { randomNumber = rand() % 100; fprintf(pFile, "%d\n", randomNumber); } printf("Succees wrtiting to File \n"); if(fclose(pFile) != 0) { printf("Error: File not closed\n"); } return 0; }

Tutorial_11_2
#include <stdio.h> #include <stdlib.h> int main(){ FILE * pFile; pFile = fopen("randomwords.txt", "r+"); char buffer[1000]; if(!pFile){ printf("Error : Couldn't Write to File\n"); return 1; } fputs("Messing With Strings", pFile); fseek(pFile, 12, SEEK_SET); fputs(" Files ", pFile); printf("Success Writing to File\n"); fseek(pFile, 0, SEEK_SET); fseek(pFile, 0, SEEK_END); long numberOfBytes = ftell(pFile); printf("Number of Bytes in File : %d\n", numberOfBytes); fseek(pFile, -20, SEEK_CUR);

30

while(fgets(buffer, 1000, pFile) != NULL){ printf("%s", buffer); } printf("\n"); if(fclose(pFile) != 0) printf("Error : File Not Closed\n"); return 0; }

31

12.
#include <stdio.h> #include <stdlib.h> #include <errno.h> int main(void){

Binary File I/O & Error Handling with C Tutorial_12

FILE *pFile; char * buffer; size_t dataInFile; long fileSize; pFile = fopen("names.bin", "rb+"); if(pFile == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); printf("File Being Created\n\n"); pFile = fopen("names.bin", "wb+"); if(pFile == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); exit(1); } } char name[] = "Derek Banas"; fwrite(name, sizeof(name[0]), sizeof(name)/sizeof(name[0]), pFile); fseek (pFile , 0 , SEEK_END); fileSize = ftell(pFile); rewind(pFile); buffer = (char*) malloc (sizeof(char)*fileSize); if(buffer == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); exit(2); } dataInFile = fread(buffer, 1, fileSize, pFile); if(dataInFile != fileSize){ perror("Error Occurred"); printf("Error Code: %d\n", errno); exit(3); } printf("%s\n", buffer); printf("\n"); fclose(pFile); free(buffer); return 0; }

Tutorial_12_2
#include <stdio.h> #include <stdlib.h> #include <errno.h>

32

int main(void){ FILE *pFile; size_t dataInFile; pFile = fopen("randomnums.bin", "rb+"); if(pFile == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); printf("File Being Created\n\n"); pFile = fopen("randomnums.bin", "wb+"); if(pFile == NULL){ perror("Error Occurred"); printf("Error Code: %d\n", errno); exit(1); } } int randomNumbers[20]; int i; for(i = 0; i < 20; i++){ randomNumbers[i] = rand() % 100; printf("Number %d is %d\n", i, randomNumbers[i]); } fwrite(randomNumbers, sizeof(int), 20, pFile); long randomIndexNumber; int numberAtIndex; printf("Which Random Number do you Want? "); scanf("%ld", &randomIndexNumber); fseek(pFile, randomIndexNumber * sizeof(int), SEEK_SET); fread(&numberAtIndex, sizeof(int), 1, pFile); printf("The Random Number at Index %d is %d\n", randomIndexNumber, numberAtIndex); fclose(pFile); return 0; }

33

13.
#include <stdio.h> #include <stdlib.h> #include <string.h>

Converting from Base 10 to Base 2, 8 and 16 Tutorial_13

char * convertBase(unsigned int numberToConvert, int base){ char buffer[33]; char *pConvertedNumber; char allValues[] = "0123456789abcdef"; if(base < 2 || base > 16) { printf("Enter a Number Between 2 and 16 \n"); exit(1); } pConvertedNumber = &buffer[sizeof(buffer)-1]; *pConvertedNumber = '\0'; do { int value = numberToConvert % base; pConvertedNumber = pConvertedNumber - 1; *pConvertedNumber = allValues[value]; numberToConvert /= base; } while(numberToConvert != 0); printf("%s", pConvertedNumber); return pConvertedNumber; } int main() { unsigned int numberOne = 60; printf("%d in Base 2 = ", numberOne); convertBase(numberOne, 2); printf("\n"); printf("%d in Base 8 = ", numberOne); convertBase(numberOne, 8); printf("\n"); printf("%d in Base 16 = ", numberOne); convertBase(numberOne, 16); printf("\n"); return 0; }

34

35

14.
#include #include #include #include #include <stdio.h> <stdlib.h> <string.h> <ctype.h> <math.h>

Convert from Others Base to Base 10 Tutorial_14

int baseToDecimal(char* number, int baseFrom, int sizeOfNumber) { int result = 0; int toThePowerOf = 0; int i; for (i = (sizeOfNumber - 2); i >= 0 ; --i) { if(isalpha(number[i])) { int charCode = ((int)tolower(number[i])) - 87; result += charCode * pow(baseFrom, toThePowerOf); } else { result += (number[i] - '0') * pow(baseFrom, toThePowerOf); } toThePowerOf++; } printf("%s in the base %d equals %d in base 10\n",number, baseFrom,result); return result; } char * convertBase(unsigned int numberToConvert, int base){ char buffer[33]; char *pConvertedNumber; char allValues[] = "0123456789abcdef"; if(base < 2 || base > 16) { printf("Enter a Number Between 2 and 16 \n"); exit(1); } pConvertedNumber = &buffer[sizeof(buffer)-1]; *pConvertedNumber = '\0'; do { int value = numberToConvert % base; pConvertedNumber = pConvertedNumber - 1; *pConvertedNumber = allValues[value]; numberToConvert /= base; } while(numberToConvert != 0); printf("%s", pConvertedNumber); return pConvertedNumber; }

36

int main() { unsigned int numberOne = 60; printf("%d in Base 2 = ", numberOne); convertBase(numberOne, 2); printf("\n"); printf("%d in Base 8 = ", numberOne); convertBase(numberOne, 8); printf("\n"); printf("%d in Base 16 = ", numberOne); convertBase(numberOne, 16); printf("\n"); char numberToConvert[] = "3C"; baseToDecimal(numberToConvert, 16, sizeof(numberToConvert)); return 0; }

37

15.

Passing Memory Addresses, Bitwise Operators, Signed Integers, Shift Operators, Twos Compliment, Bit Masking Tutorial 15

#include #include #include #include #include

<stdio.h> <stdlib.h> <string.h> <ctype.h> <math.h>

int baseToDecimal(char* number, int baseFrom, int sizeOfNumber) { int result = 0; int toThePowerOf = 0; int i; for (i = (sizeOfNumber - 2); i >= 0 ; --i) { if(isalpha(number[i])) { int charCode = ((int)tolower(number[i])) - 87; result += charCode * pow(baseFrom, toThePowerOf); } else { result += (number[i] - '0') * pow(baseFrom, toThePowerOf); } toThePowerOf++; } printf("%s in the base %d equals %d in base 10\n",number, baseFrom,result); return result; } char * convertBase(unsigned int numberToConvert, int base, char *pConvertedNumber){ char allValues[] = "0123456789abcdef"; if(base < 2 || base > 16) { printf("Enter a Number Between 2 and 16 \n"); exit(1); } pConvertedNumber[32] = '\0'; do { int value = numberToConvert % base; pConvertedNumber = pConvertedNumber - 1; *pConvertedNumber = allValues[value]; numberToConvert /= base; } while(numberToConvert != 0); return pConvertedNumber; } int main() { unsigned int numberSix = 6; unsigned int numberSeven = 7;

38

char *pConvertedNumber; pConvertedNumber = malloc(33 * sizeof(char)); printf("%s\n", convertBase(numberSix,2,pConvertedNumber)); unsigned int andSolution = numberSix & numberSeven; unsigned int orSolution = numberSix | numberSeven; unsigned int exOrSolution = numberSix ^ numberSeven; unsigned int onesCompSoultion = ~numberSix; unsigned int shitfLeftTwo = numberSix << 2; unsigned int analyzeMyBits = 170; //10101010 unsigned int theMask = 15; // 00001111 unsigned int last4Bits = analyzeMyBits & theMask; printf("%s & ", convertBase(numberSix,2,pConvertedNumber)); printf("%s = ", convertBase(numberSeven,2, pConvertedNumber)); printf("%s \n\n ", convertBase(andSolution, 2, pConvertedNumber)); printf("%s | ", convertBase(numberSix,2,pConvertedNumber)); printf("%s = ", convertBase(numberSeven,2, pConvertedNumber)); printf("%s \n\n ", convertBase(orSolution, 2, pConvertedNumber)); printf("%s ^ ", convertBase(numberSix,2,pConvertedNumber)); printf("%s = ", convertBase(numberSeven,2, pConvertedNumber)); printf("%s \n\n ", convertBase(exOrSolution, 2, pConvertedNumber)); printf("~%s = ", convertBase(numberSix,2, pConvertedNumber)); printf("%s\n\n",convertBase(onesCompSoultion, 2, pConvertedNumber)); printf("%s << 2 = ", convertBase(numberSix,2, pConvertedNumber)); printf("%s = %d\n\n",convertBase(shitfLeftTwo, 2, pConvertedNumber), shitfLeftTwo); printf("%s & ", convertBase(analyzeMyBits,2,pConvertedNumber)); printf("%s = ", convertBase(theMask,2, pConvertedNumber)); printf("%s \n\n ", convertBase(last4Bits, 2, pConvertedNumber)); free(pConvertedNumber); return 0; }

39

40

41

Vous aimerez peut-être aussi