Variable length binary number to signed integer representation

17 ビュー (過去 30 日間)
Andrew Campbell
Andrew Campbell 2021 年 5 月 28 日
回答済み: Walter Roberson 2021 年 5 月 28 日
I have a variable length text representation of a binary number up to 64 "bits" long. I want to be able to convert this back to a singed integer representation of the number.
This is what I have so far, but a few problems are encountered:
binNum = '11000000' %for example decimal 192, I want it to be read as -64
typecast(uint64(bin2dec(binNum)),'int64')
issues:
  1. the leading '1' is dropped and not read in correctly
  2. if appending 1's to the front to fill up the 64 bits maximum, bin2dec only supports 53 bits
  3. unit8 cannot be used since binNum can be from 1 bit in size to 64 bits
I am thinking I will need to write my own funciton, but was wondering if there was a built in way to handle this problem

採用された回答

Walter Roberson
Walter Roberson 2021 年 5 月 28 日
binNum = '11000000';
bin64 = uint64([repmat(binNum(1), 1, 64-length(binNum)), binNum] - '0')
bin64 = 1×64
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
outu64 = sum(bin64 .* uint64(2).^uint64(63:-1:0), 'native')
outu64 = uint64 18446744073709551552
fprintf('%016x', outu64)
ffffffffffffffc0
outs64 = typecast(outu64, 'int64')
outs64 = int64 -64

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by