Character to Binary function?
조회 수: 78 (최근 30일)
이전 댓글 표시
I need to create a function that will: accept a character and returns a vector of 8 logical values (bits) that are the binary equivalent of the ASCII value of the character, while using functions dec2bin, sprintf, and logical. While converting the 0's and 1's to ASCII codes, we aren't supposed to use a if statement, we're supposed to follow these rules:
If you have the character '0' (which in Matlab is the same as the number 48), how would you convert that 48 into a 0? In other words, how do you get from 48 to 0? How do you get from 49 to 1? Or for that matter, how would you get from 50 to 2? The relationship is the same in each case.
I'm not sure where to get started on this function, any help would be great, thanks in advance!!
From what I understand, we need to accept a character, then convert it to ASCII (not sure how to do this), then output a vector of 8 bits (0s and 1s). So far, I know a 0 is 48 in ASCII, but when I use dec2bin, i get:
110100
111000
So i'm not really sure where to go from there.
댓글 수: 0
답변 (2개)
Image Analyst
2014년 11월 24일
편집: Image Analyst
2014년 11월 24일
Subtraction seem like the obvious operation that they were hinting strongly at. Did you try subtraction:
ch = '0' % or anything from '0' - '9'
decimalValue = ch - '0'
dec2bin(ch) % Binary of the ascii value.
dec2bin(decimalValue) % Binary of the decimal value
I trust you can take it from there.
댓글 수: 8
Image Analyst
2014년 11월 25일
This works bot both numbers and characters in a string. For example '123abc'.
function asciiLogicalArray = char2bin()
clc;
userInput = input('Enter a numerical digit : ', 's')
% userInput is the ASCII value of the digit. So for 2, the value is 50.
decimalValue = userInput
% Get the binary value of the ascii value of the
% characters in a string (a character array).
% For example, for 2, strAscii will be 110010 (which = 50 in decimal).
strAscii = dec2bin(userInput) % Binary of the ascii value.
% Convert row-wise to a row vector
strAscii = reshape(strAscii', [1, numel(strAscii)])
% Convert the binary string into a logical array.
% So for example, 2 = 50 = 110110 will be a logical array [1,1,0,1,1,0]
asciiLogicalArray = logical(strAscii - 48)
Thorsten
2014년 11월 24일
c = input('Enter a character > ', 's');
binvecc = logical(dec2bin(c, 8) - '0');
sprintf('%x', binvecc)
댓글 수: 4
참고 항목
카테고리
Help Center 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!