Reputation: 539
I have a matrix with decimal numbers and I know I can convert them to binary using this code:(IEEE 754 double-precision binary)
m = reshape(dec2bin(typecast(b(:),'uint8'),8).',1,[]);
b_recovered = reshape(typecast(uint8(bin2dec(reshape(m,8,[]).')),'double'),size(b));
Using this code, I think 8 last bits are most significant bits. I want to generate random decimal numbers and replace these elements as 8 last bits won't change after replacing with generated random numbers. I need to have a new number while keeping 8 last bits.
For example:
b=-1.12;
m=1110110001010001101110000001111010000101111010111111000110111111;
be replaced by:
m=0000110000000000001110000000011010000001100010000010000110111111;
Which is equal to:
b=-1.337678432804527e-04
I know that I can generate random decimal numbers between two numbers but I'm not sure how to solve the above mentioned problem.
mymatrix(1:q,:)= value2 + (value2-value1).*rand(q,size(y_blk,2));
Upvotes: 0
Views: 564
Reputation: 1264
Keeping the first 56 replacing the last 8
Generate an integer between 0
and 255
and convert it to binary. Replace the first/last 8 bits of you sequence with them.
b=-1.12;
m = reshape(dec2bin(typecast(b(:),'uint8'),8).',1,[]);
m_small = [dec2bin(randi(256)-1,8), m(9:end)]
m_large = [m(1:end-8),dec2bin(randi(256)-1,8)]
b_small = reshape(typecast(uint8(bin2dec(reshape(m_small,8,[]).')),'double'),size(b));
b_large = reshape(typecast(uint8(bin2dec(reshape(m_large,8,[]).')),'double'),size(b));
The value of b_small
, hardly change indicating that the first 8bits are the least significant. b_large
change is massive so the last 8 are the most significant bits.
Keeping the last 8 replacing the first 56
Misunderstood the question you want to keep the last 8 bits and replace the rest. In that case generate 56bits random data and add the last 8 that you have saved. Now as it turns out Matlab can only generate a max int of 2^53
. Instead of generating one integer up to 2^56
, generate 7 each one being 2^8
, and concatenate them.
m_new = [reshape(dec2bin(randi(2^8,[7,1])-1,8),[1,56]), m(end-7:end)]
b_new = reshape(typecast(uint8(bin2dec(reshape(m_new,8,[]).')),'double'),size(b));
Upvotes: 1