-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChar2ByteArray.m
More file actions
44 lines (42 loc) · 1.44 KB
/
Char2ByteArray.m
File metadata and controls
44 lines (42 loc) · 1.44 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
function byte = Char2ByteArray(character)
% Function Char2ByteArray converts an ASCII character into the equivalent
% 8-element array of 1s and 0s (representing a binary number)
% Input:
% character: A single ASCII character
% Output:
% byte: An 8 element 1D array of 0s and 1s representing a single byte of
% information. The binary number corresponds to the number of the ASCII
% character passed in. The output should be a row vector of type uint8
%
% Author: Henry Huang
c = double(character);
byte = zeros(1,8,"uint8"); % initialise byte array aswell as setting it to uint8 class
i = 8;
while c > 0
remainder = mod(c, 2); % find remainder of current bit
byte(i) = remainder;
c = floor(c / 2); % Update c for next iteration
i = i - 1; % Move to next most significant bit
end
end
% if c >=128
% for i=8:-1:1 % If character decimal equivalent is 128 or greater then 1 would be first value
% if mod(c,2) == 1 % Division method while finding remainder for bit
% byte(i) = 1;
% c = (c-1)/2;
% else
% byte(i) = 0;
% c = c/2;
% end
% end
% else
% for i=8:-1:2 % Else, character decimal equivalent is less than 128 then 0 would be first value
% if mod(c,2) == 1 % Division method while finding remainder for bit
% byte(i) = 1;
% c = (c-1)/2;
% else
% byte(i) = 0;
% c = c/2;
% end
% end
% end