How can I convert a negative integer to a binary string, in other words, how can I find Two's Complement in MATLAB?
이 질문을 팔로우합니다.
- 팔로우하는 게시물 피드에서 업데이트를 확인할 수 있습니다.
- 정보 수신 기본 설정에 따라 이메일을 받을 수 있습니다.
오류 발생
페이지가 변경되었기 때문에 동작을 완료할 수 없습니다. 업데이트된 상태를 보려면 페이지를 다시 불러오십시오.
이전 댓글 표시
DEC2BIN converts non-negative decimal integers to a binary string. I want to create binary strings, with a leading sign bit, from any (negative or positive) integer.
채택된 답변
This can be accomplished using the TYPECAST function. For example, to find a binary string for 'n' with respect to 8-bit two's complement, you can use the command,
dec2bin(typecast(int8(n),'uint8'))
댓글 수: 6
dec2bin(typecast(10.2,'uint64'))
You are incorrect. The binary equivalent of 10.2 involves an infinite repeating decimal, the same way that the decimal representation of 1/7 involves an infinite repeating decimal.
There is no one representation in binary for negative values or for fractions. There are several competing standards for faking it. One of the standards is known as IEEE 754 Double Precision. It is that standard which MATLAB uses to represent numbers in binary. dec2bin(typecast(10.2,'uint64'),64) gives you the string representation of the binary used for 10.2
As to how to get back to the 10.2... with difficulty. Which is why people do not use this method.
Actually checking again I find it doesn't quite work. Instead you need
x = -10.2;
z2 = reshape(dec2bin(typecast(x,'uint8'),8).',1,[])
and you recover with
typecast(uint8(bin2dec(reshape(z2,8,[]).')),'double')
If you want to get back exactly what you started with, you need to use this (or equivalent.) Or, alternately, you could define your own format with precision sufficient for your needs. Be sure to take into account how you represent negatives and how you represent a potentially large range of values.
If x is a matrix then the conversion to binary is the same, but after the code for converting back you need to reshape() to appropriate size.
reshape() it to vector.
You cannot get back the correct number if you convert -5.82 to fewer bits.
value = -5.82;
bits32 = dec2bin(typecast(single(value),'uint32'))
retrieved = typecast(uint32(bin2dec(bits32)),'single');
value - retrieved
ans =
single
1.716614e-07
The best retrieved value you can get differs from the original by about 3 parts per billion.
Sure there are other ways to generate 32 bit representations of double precision numbers, but think about this for a moment:
There are at most 2^32 different 32 bit numbers.
In double precision, for any given floating point mantissa, there are 52 bits of fraction, so thare are at least 2^52 different double precision numbers. For example 1 + (0:2^52-1)/2^53 constructs 2^52 different double precision floating point numbers with the same mantissa:
>> num2hex(1)
ans =
'3ff0000000000000'
>> num2hex(2-eps)
ans =
'3fffffffffffffff'
>> log2(eps)
ans =
-52
By the Pigeon Hole principle, it is obvious that you cannot come even close to representing all possible double precision numbers in 32 bits. No matter what encoding you use for the 32 bits, there are at most 2^32 different states, and that is not enough to encode 2^52 different values.
추가 답변 (0개)
카테고리
도움말 센터 및 File Exchange에서 Data Type Conversion에 대해 자세히 알아보기
제품
참고 항목
2013년 6월 26일
2020년 10월 2일
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!웹사이트 선택
번역된 콘텐츠를 보고 지역별 이벤트와 혜택을 살펴보려면 웹사이트를 선택하십시오. 현재 계신 지역에 따라 다음 웹사이트를 권장합니다:
또한 다음 목록에서 웹사이트를 선택하실 수도 있습니다.
사이트 성능 최적화 방법
최고의 사이트 성능을 위해 중국 사이트(중국어 또는 영어)를 선택하십시오. 현재 계신 지역에서는 다른 국가의 MathWorks 사이트 방문이 최적화되지 않았습니다.
미주
- América Latina (Español)
- Canada (English)
- United States (English)
유럽
- Belgium (English)
- Denmark (English)
- Deutschland (Deutsch)
- España (Español)
- Finland (English)
- France (Français)
- Ireland (English)
- Italia (Italiano)
- Luxembourg (English)
- Netherlands (English)
- Norway (English)
- Österreich (Deutsch)
- Portugal (English)
- Sweden (English)
- Switzerland
- United Kingdom (English)
