blob: 03d1bd04951a69c4c71bc49f316af8140327a856 (
about) (
plain)
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
|
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>
#include <string.h>
bool is_int_positive( int test_int ){
/*
multiply test_int by 2 to get the amount of characters/bits
that would be in the hexadecimal value.
For example:
8-bit unsigned/signed = 1 * 2 = 2 (0x00 - 0xFF)
16-bit unsigned/signed = 2 * 2 = 4 (0x0000 - 0xFFFF)
32-bit unsigned/signed = 4 * 2 = 8 (0x00000000 - 0xFFFFFFFF)
64-bit unsigned/signed = 8 * 2 = 16 (0x0000000000000000 - 0xFFFFFFFFFFFFFFFF)
*/
size_t value_bits = sizeof(test_int) * 2;
/*
Next check if first bit is 1 (positive integer) or 0 (negative integer).
To do this the value bits must be used to right shift by the value bits count
so only the MSB is left.
*/
size_t value_bits_shift = test_int >> (value_bits - 1);
/*
Now do bitwise and operation to compare if the MSB is 1 (negative) or 0 (positive).
This works because the MSB tells if the integer contained in following bits should be taken
as positive or negative integer.
For positive integers the MSB is 0 and for negative integers the MSB is set to 1.
Because value_bits_shift was shifted right by value_bits minus 1 the result is
being left with just the bit containing the MSB value.
The bitwise and below checks if the MSB is not 1 then return true (positive integer) and otherwise false (negative integer).
*/
return (!(value_bits_shift & 0x1)) ? true : false;
}
int main( int argc, char **args ){
// Positive integer
int first_int = 12345;
// Negative integer
int second_int = -12345;
// Third integer that is just under 0
int third_int = -1;
// Fourth integer to test
int fourth_int = 1;
// Check the first integer
fprintf( stdout, "Result for positive integer: %i\n", is_int_positive(first_int) );
// Now do the same for the second one
fprintf( stdout, "Result for negative integer: %i\n", is_int_positive(second_int) );
// Third integer
fprintf( stdout, "Result for third integer that is -1: %i\n", is_int_positive(third_int) );
// Fourth integer
fprintf( stdout, "Result for fourth integer that is just positive by one: %i\n", is_int_positive(fourth_int) );
exit( EXIT_SUCCESS );
}
|