Want to convert whole data in a binary/ text file in to binary digits
5 次查看(过去 30 天)
显示 更早的评论
I want to convert the data in the file to be read as HexaDecimal Characters Array.
Or to read the same data as binary Array.
I have a file 1.txt containing Hex data
"0F 89 03 CC 14 77 04 1B F4 F0 A6 61 29 85 3D A0 14 98 B1 DB E6 E7 F4 FC 20 F0 26 09 75 C7 " + ...
"95 AB 83 77 18 3B F0 00 73 30 52 CF 7D 5A 15 8E B9 4F A8 2E B7 F1 FB EE 08 6D C2 A1 28 87 " + ...
"D6 F6 6D 5B 11 54 B2 B8 E5 18 E3 75 CF 39 DC 5F C3 0E D5 29'"
I want to get the binary representation of each hex character in a Array.
kindly help me how to read the file as Hex Characters and convert the whole hex characters to binary array.
0000 1111 1000 1001 0000 0011 1100 1100 0001 0100 0111 0111 0000 0100 0001 1011 1111 0100
1111 0000 1010 0110 0110 0001 0010 1001 1000 0101 0011 1101 1010 0000 0001 0100 1001 1000
1011 0001 etc
0 个评论
回答(2 个)
dpb
2022-8-29
To use native I/o conversion, hex values must be preceded by '0x' so will either need to do that string substitution or read as string data -- will illustrate the latter.
t=readlines('1.txt'); % read the file as string array -- unknown shape
t=t(~isempty(t)); % readlines will return empty string if is \n at end of file
t=strtrim(split(t)); % return the "words" of the string
d=dec2bin(hex2dec(t),8); % display bits -- result is char() array.
The numeric values are available in memory if you stop after the hex2dec step; there is no builtin C (and hence none in MATLAB) format specifier to display binary output; only for hexadecimal or octal. Hence the dec2bin above to show on screen.
You don't give us any info on what your end objective is here, but, don't get confused about the display of the value vis a vis the numeric value and memory storage. Whether you look at the decimal or hex or binary representation on the screen, the value in memory is the same.
3 个评论
Walter Roberson
2022-8-30
readlines() requires R2020b or newer. You did not enter your MATLAB release when you created the question.
The equivalent of
t=readlines('1.txt');
in earlier releases would be
t = string( regexp(fileread('1.txt'), '\r?\n', 'split') );
Walter Roberson
2022-8-30
t=strtrim(split(t)); % return the "words" of the string
If I recall, that would fail if each string() entry did not have exactly the same number of "words" -- which could be the case if the final line was shorter.
Walter Roberson
2022-8-30
fopen the file. fscanf with %2x format. fclose the file. uint8() the data read.
Now you have uint8 data and can convert it into binary any way that makes sense to you.
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Text Files 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!