Advertisement
Guest User

Untitled

a guest
Aug 22nd, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.57 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3.  
  4.  
  5. /*
  6. INFO: This snippet is one of the "Extra Credit" assignments from Chapter 11 "Arrays and Strings" from LCTHW.
  7. The snippet uses the memcpy function to copy the bytes from a char array into an integer, since an integer takes up 4 bytes of space,
  8. and an array of char's takes N bytes, where N = its length.
  9. Here's a chart explaining how the result gets evaluated (the char's ASCII code is evaluated when I say '1st' * x, etc):
  10.  
  11.  
  12. N of Args
  13. 1 -> 1st
  14. 2 -> 1st + 2nd * (256)
  15. 3 -> 1st + 2nd * (256) + 3rd * (256^2)
  16. 4 -> 1st + 2nd * (256) + 3rd * (256^2) + 4th * (256^3)
  17.  
  18. */
  19.  
  20. //Change this to affect how large the array for the char's will be
  21. //Can't be larger than 4 else the integer storing the result is guaranteed to overflow (too large)
  22. #define CHAR_ARRAY_SIZE 4
  23.  
  24. int main(int argc, char *argv[])
  25. {
  26. char array[CHAR_ARRAY_SIZE] = {'a', 'b', 'c', '\\'};
  27. int result[1] = { 0 };
  28.  
  29. memcpy( result, array, CHAR_ARRAY_SIZE);
  30.  
  31. printf("\n---- Overview of Operation ----\n");
  32.  
  33. printf("Integer 'result' size: %ld bytes\nChar array size: %ld bytes\n",
  34. sizeof(result), sizeof(array));
  35.  
  36. for(int i=0; i < CHAR_ARRAY_SIZE; i++) {
  37. printf("Arg #%d = '%c' (%d)\n",
  38. i+1, array[i], array[i]);
  39. }
  40.  
  41. printf("Calculation of your result:\n");
  42. for(int i=0; i < CHAR_ARRAY_SIZE; i++) {
  43. if(i != 0 && i != CHAR_ARRAY_SIZE)
  44. printf(" + ");
  45. printf("%d * (256^%d)", array[i], i);
  46. }
  47.  
  48. printf("\nResult = %d\n", result[0]);
  49.  
  50. return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement