1

I am learning MATLAB and am facing problem about extracting most significant bits from a given double. I saw getmsb function. But, is there a function that can give me say 5 most significant bits?

Anil.

Matthew Simoneau
  • 6,199
  • 6
  • 35
  • 46
Anil Katti
  • 1,313
  • 1
  • 14
  • 26
  • Do you want the 5 MSBs as if it were an integer? Or do you want the 5 MSBs in it's floating point representation? – Pablo Apr 17 '11 at 03:15

1 Answers1

1

It's late, so I'm sure there's a better solution. Anyway, this seems to do it:

A = rand(1, 1) * 10000
nBits = 5
curBits = ceil(log2(A))
toShift = curBits - nBits
wantedMSB = fix(A / 2^toShift) % This is still a double, feel free to cast.
dec2bin(wantedMSB)             % Result in bitstring form.

Or, as one liner:

A = rand(1, 1) * 10000
nBits = 5
wantedMSB = fix(A / 2^(ceil(log2(A)) - nBits))

[Edit] Btw, the getmsb function is part of the Fixed-Point Toolbox, which might not be available on every MATLAB installation.

AVH
  • 11,349
  • 4
  • 34
  • 43