2

I would like to save each byte of a uint_32 number to the elements of a 1x4 matrix using Matlab

a = zeros(1,4,'uint8');
val = uint32(2^32-1);

How can I split val byte-wise and insert each single element in the array?

UserK
  • 884
  • 3
  • 17
  • 40

2 Answers2

2

You may use the typecast function, which converts between data types without changing the underlying data:

a = typecast(uint32(2^32-1), 'uint8')
% produces the array [255 255 255 255]
nneonneo
  • 171,345
  • 36
  • 312
  • 383
  • What about a floating point number? Let's say val = 1,23. What should I specify in the number type option? – UserK Nov 13 '14 at 22:33
1

From what I could understood, I think you are looking for something like this with the least significant byte going as the rightmost element in the output vector -

bits = reshape(bitget(num,32:-1:1),8,[]); %// num is the input number
weights2 = 2.^([7:-1:0]);
out = weights2*bits
Divakar
  • 218,885
  • 19
  • 262
  • 358
  • If you try `bits = reshape(bitget(uint32(1234),32:-1:1),8,[]);` matlab will return: `Error using * MTIMES is not fully supported for integer classes. At least one input must be scalar. To compute elementwise TIMES, use TIMES (.*) instead.` How to solve – UserK Nov 14 '14 at 17:18
  • 1
    @narutov6 That `num` has to be in `double` format. So, you need to convert that to `double` before using it. Thus, if you have num = `uint32(1234)`, do this - `bits = reshape(bitget(double(num),32:-1:1),8,[]);` . Hope this works out and make sense to you! – Divakar Nov 14 '14 at 17:26
  • I'm using a slider's value as number. I get the following error: `Error using bitget Double inputs must have integer values in the range of ASSUMEDTYPE. bits = reshape(bitget(double(get(pidKpSlider,'Value')*1000),32:-1:1),8,[]);` – UserK Nov 14 '14 at 18:12
  • 1
    @narutov6 most probably the slider isn't feeding integer values. So, how about wrap it with `round` : `...double(round(get(pid..)`? – Divakar Nov 14 '14 at 18:14
  • @narutov6 Haha de nada! ;) – Divakar Nov 14 '14 at 18:38