SDDSlib
Loading...
Searching...
No Matches
binary.c
Go to the documentation of this file.
1/**
2 * @file binary.c
3 * @brief Contains binary conversion functions sbinary and bitsSet.
4 *
5 * @copyright
6 * - (c) 2002 The University of Chicago, as Operator of Argonne National Laboratory.
7 * - (c) 2002 The Regents of the University of California, as Operator of Los Alamos National Laboratory.
8 *
9 * @license
10 * This file is distributed under the terms of the Software License Agreement
11 * found in the file LICENSE included with this distribution.
12 *
13 * @author M. Borland, C. Saunders, R. Soliday
14 */
15
16#include "mdb.h"
17
18char *sbinary(char *s, int len, long number) {
19 long pow_of_2, n, i;
20 char c;
21
22 pow_of_2 = 1;
23 n = 0;
24 strcpy_ss(s, "0");
25 while (pow_of_2 > 0 && pow_of_2 <= number && n < len - 1) {
26 if (pow_of_2 & number) {
27 number -= pow_of_2;
28 s[n] = '1';
29 } else
30 s[n] = '0';
31 s[++n] = 0;
32 pow_of_2 = pow_of_2 << 1;
33 }
34 i = -1;
35 while (--n > ++i) {
36 c = s[n];
37 s[n] = s[i];
38 s[i] = c;
39 }
40 return (s);
41}
42
43/**
44 * @brief Counts the number of set bits (1s) in the given data.
45 *
46 * This function iterates through each bit of the provided unsigned
47 * long integer and counts how many bits are set to 1.
48 *
49 * @param data The unsigned long integer to count set bits in.
50 * @return The number of set bits.
51 */
52long bitsSet(unsigned long data) {
53 long i = 0;
54 while (data) {
55 if (data & 1)
56 i++;
57 data >>= 1;
58 }
59 return i;
60}
long bitsSet(unsigned long data)
Counts the number of set bits (1s) in the given data.
Definition binary.c:52
char * strcpy_ss(char *dest, const char *src)
Safely copies a string, handling memory overlap.
Definition str_copy.c:34