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?

1
  • 1
    Note that uint32(2^32) is zero. Commented Nov 10, 2014 at 19:08

2 Answers 2

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]
Sign up to request clarification or add additional context in comments.

1 Comment

What about a floating point number? Let's say val = 1,23. What should I specify in the number type option?
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

5 Comments

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
@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!
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,[]);
@narutov6 most probably the slider isn't feeding integer values. So, how about wrap it with round : ...double(round(get(pid..)?
@narutov6 Haha de nada! ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.