How are uint8 calculated? And how can I convert them back to Integers in Codesys?

8 views (last 30 days)
I am converting a Struct containing integers to a uint8
data = struct('Header', [], 'Pos', []);
data.Header = 1010;
data.Pos = double([81, -17, 8651]);
uintHeader = typecast(data.Header, 'uint8');
uintPos = typecast(data.Pos, 'uint8');
dataArray = [uintHeader uintPos];
dataArray = 0 0 0 0 0 144 143 64 0 0 0 0 0 64 84 64 0 0 0 0 0 0 49 192 0 0 0 0 128 229 192 64
How do i get from '1010' to '0 0 0 0 0 144 143 64' etc.?
I then send this array to a system that runs on Codesys.
Is there a function in Codesys, which can convert it back to the original integers?
  3 Comments
Michael
Michael on 20 Dec 2023
Since 'Header' is a 64 bit float number the representation in hexadecimal format is
format hex
1010
ans =
408f900000000000
and each byte in ascending order
format short
uint8([0x0 0x0 0x0 0x0 0x0 0x90 0x8f 0x40])
ans = 1×8
0 0 0 0 0 144 143 64

Sign in to comment.

Accepted Answer

Varun
Varun on 26 Dec 2023
Edited: Varun on 26 Dec 2023
Hi Tim,
I understand that you are using the MATLAB functions “typecast” as below:
uintHeader = typecast(data.Header, 'uint8');
To know about working of “typecast”, consider an example:
x=unit32(256);
y=typecast(x,'unit8');
To represent decimal 256, 8 bits are not enough, you need minimum 9 bits. It can be easily stored in 32 bits but how can it be stored in 8 bits. You can see that we are trying to typecast 256 into “uint8” i.e., only 8 bits.
So, the “typecast” function splits this 32-bit representation of 256 into 4 chunks each with 8 bits or 1 byte. It then uses little-endian convention to produce the following row vector where each element is of type “uint8”.
y =
1×4 uint8 row vector
0 1 0 0
If “x” was of 64 bits, then it would have split into 64/8 = 8 chunks and calculate each chunk value independently and store them in the row vector using the little-endian convention.
Please refer to the following MATLAB documentation for “typecast”:
Now, answering your 2nd part of the question where you want to convert back from this “uint8” vector notation back to original “uint32” integer in CODESYS. You can refer to the following example:
VAR
Y: ARRAY[0..11] OF BYTE; // Your array of bytes
X: ARRAY[0..2] OF UDINT; // Resulting array of 32-bit unsigned integers
END_VAR
// Assume Y is your 12-element array of bytes
X[0] := BYTE_TO_UDINT(Y[0 TO 3]);
X[1] := BYTE_TO_UDINT(Y[4 TO 7]);
X[2] := BYTE_TO_UDINT(Y[8 TO 11]);
Please refer to the following CODESYS tutorials:
Operator ‘<INT Type>_TO_<INT Type>’:
Data types:

More Answers (0)

Community Treasure Hunt

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

Start Hunting!