-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbytes.c
More file actions
117 lines (101 loc) · 2.73 KB
/
bytes.c
File metadata and controls
117 lines (101 loc) · 2.73 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include "bytes.h"
void print_bytes(byte *bytes, unsigned int length) {
unsigned int i;
for (i = 0; i < length; ++i) {
printf("%02x", bytes[i]);
}
}
void print_bits(byte *bits, unsigned int length) {
unsigned int i;
for (i = 0; i < length; ++i) {
if (bits[i] == 0 || bits[i] == 1)
printf("%d", bits[i]);
}
}
void byte_to_bit_array(/*IN*/ byte *bytes, unsigned int bytelength, /*OUT*/ byte *bits) {
unsigned int i, j;
byte b;
for (i = 0; i < bytelength; ++i) {
b = bytes[i];
for (j = 0; j < 8; ++j) {
bits[i * 8 + j] = (b & (1 << (7 - j))) != 0;
}
}
}
void bit_to_byte_array(/*IN*/ byte *bits, unsigned int bitslength, /*OUT*/ byte *bytes) {
unsigned int i, j;
byte b;
for (i = 0; i < bitslength / 8; ++i) {
b = 0;
for (j = 0; j < 8; ++j) {
b += bits[i * 8 + j] << (7 - j);
}
bytes[i] = b;
}
}
byte *generate_random_bytes(unsigned int length) {
assert(length % 4 == 0);
byte *bytes = malloc(length);
unsigned int i;
for (i = 0; i < length; i += 4) {
uint32_t r = sfmt_genrand_uint32(&mtrand);
bytes[i] = (r >> 24);
bytes[i+1] = (r >> 16) & 0xff;
bytes[i+2] = (r >> 8) & 0xff;
bytes[i+3] = r & 0xff;
}
return bytes;
}
byte *generate_random_bits(unsigned int bitlength) {
assert(bitlength % 8 == 0);
byte *bytes = generate_random_bytes(bitlength / 8);
byte *bits = malloc(bitlength);
byte_to_bit_array(bytes, bitlength / 8, bits);
free(bytes);
return bits;
}
void xor_bytes(/*IN*/ byte *b1, /*IN*/ byte *b2, /*OUT*/ byte *result, unsigned int length) {
unsigned int i;
for (i = 0; i < length; ++i) {
result[i] = b1[i] ^ b2[i];
}
}
unsigned int isset_bit(byte *b, int pos) {
return (b[pos/8] & (128 >> (pos%8)));
}
void set_bit(byte *b, int pos) {
b[pos/8] |= (128 >> (pos%8));
}
void unset_bit(byte *b, int pos) {
b[pos/8] &= 255 - two_power(7 - (pos%8));
}
void flip_bit(byte *b, int pos) {
b[pos/8] ^= (128 >> (pos%8));
}
unsigned int hamming_weight(byte *b, unsigned int length) {
unsigned int w = 0;
unsigned int i, x;
for (i = 0; i < length; ++i) {
// http://stackoverflow.com/a/14010273/1198623
x = b[i];
x = (x & 0x55) + (x >> 1 & 0x55);
x = (x & 0x33) + (x >> 2 & 0x33);
x = (x & 0x0f) + (x >> 4 & 0x0f);
w += x;
}
return w;
}
void inc_byte(byte *b, int idx) { // idx = bytelength-1 (last index)
if (b[idx] < 0xff) {
b[idx]++;
return;
}
b[idx] = 0x00;
if (idx == 0)
return;
//idx--;
inc_byte(b, idx - 1);
}