forked from jkurian49/ece160-hw02
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hw02.c
83 lines (71 loc) · 2.17 KB
/
hw02.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <stdio.h>
#include <stdlib.h>
/*
Prints the sizes and possible ranges of four integer data types.
*/
void print_int_ranges() {
// These are made up numbers that will not be correct on most systems!
// TODO correctly compute these values!
char short_bytes = sizeof(short);
char int_bytes = sizeof(int);
char uint_bytes = sizeof(unsigned int);
char long_bytes = sizeof(long int);
short short_min = 1 << (short_bytes * 8 - 1);
short short_max = ~short_min;
long int_min = 1 << (int_bytes * 8 - 1);
long int_max = ~int_min;
unsigned int uint_min = 0;
unsigned int uint_max = ~uint_min;
long long_min = 1L << (long_bytes * 8 - 1);
long long_max = ~long_min;
// Keep these exact printf commands :)
printf("short is %d bytes or %d bits and ranges from %d to %d\n",
short_bytes, short_bytes * 8, short_min, short_max);
printf("int is %d bytes or %d bits and ranges from %d to %d\n",
int_bytes, int_bytes * 8, int_min, int_max);
printf("long is %d bytes or %d bits and ranges from %ld to %ld\n",
long_bytes, long_bytes * 8, long_min, long_max);
printf("unsigned int is %d bytes or %d bits and ranges from %u to %u\n",
uint_bytes, uint_bytes * 8, uint_min, uint_max);
}
/*
Takes in an integer value v and a integer bit index i
Returns 1 if bit i in value v equals 1
Returns 0 if bit i in value v equals 0
*/
int is_bit_set(unsigned char v, unsigned char i) {
if (i >= sizeof(unsigned char) * 8) {
fprintf(stderr, "Index out of range!\n");
return 0;
}
char mask = 1 << i;
if (v & mask) {
return 1;
}
return 0;
}
/*
Don't touch anything in main!
*/
int main(int argc, char* argv[])
{
if (argc < 3) {
fprintf(stderr, "Not enough arguments!\n");
return -1;
}
print_int_ranges();
unsigned char value = atoi(argv[1]);
unsigned char bit = atoi(argv[2]);
int is_set = is_bit_set(value, bit);
switch(is_set) {
case 1:
printf("Bit %u in value %u is set\n", bit, value);
break;
case 0:
printf("Bit %u in value %u is not set\n", bit, value);
break;
default:
fprintf(stderr, "is_bit_set returned an invalid value!\n");
}
return 0;
}