SDDSlib
Loading...
Searching...
No Matches
binary.c File Reference

Contains binary conversion functions sbinary and bitsSet. More...

#include "mdb.h"

Go to the source code of this file.

Functions

char * sbinary (char *s, int len, long number)
 
long bitsSet (unsigned long data)
 Counts the number of set bits (1s) in the given data.
 

Detailed Description

Contains binary conversion functions sbinary and bitsSet.

License
This file is distributed under the terms of the Software License Agreement found in the file LICENSE included with this distribution.
Author
M. Borland, C. Saunders, R. Soliday

Definition in file binary.c.

Function Documentation

◆ bitsSet()

long bitsSet ( unsigned long data)

Counts the number of set bits (1s) in the given data.

This function iterates through each bit of the provided unsigned long integer and counts how many bits are set to 1.

Parameters
dataThe unsigned long integer to count set bits in.
Returns
The number of set bits.

Definition at line 52 of file binary.c.

52 {
53 long i = 0;
54 while (data) {
55 if (data & 1)
56 i++;
57 data >>= 1;
58 }
59 return i;
60}

◆ sbinary()

char * sbinary ( char * s,
int len,
long number )

Definition at line 18 of file binary.c.

18 {
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}
char * strcpy_ss(char *dest, const char *src)
Safely copies a string, handling memory overlap.
Definition str_copy.c:34