emtiajium
emtiajium

Reputation: 81

Matlab data type specification

I have a problem with data type in MATLAB. It's a simple code of converting binary to decimal. For my further task, those should be integer 64 bit. How can I do it?

This code converts those value into double. And, type casting isn't helpful; for example, for the first value, sum is 4.0265e+09 but after casting via Y = typecast(sum, 'int64'); it generates 4750734656922451968 which is not correct value.

example.png:

enter image description here

I = imread('example.png');
level = graythresh(I);
img = im2bw(I,level);

sz=size(img);
for i=1:sz(1)
    sum=0;
    p=1;
    for j=sz(2):-1:1
        sum=sum+img(i,j)*p;
        p=p*2;
    end
    disp(sum);
end

Upvotes: 0

Views: 165

Answers (1)

IKavanagh
IKavanagh

Reputation: 6187

You should use cast instead of typecast

>> s = 4.0265e+09;
>> cast(s, 'int64')
ans =
    4026500000

typecast converts data without altering the underlying byte values whereas cast converts data and attempts to keep the same value. typecast as you have found can change the value of data as it does not alter the underlying byte values. typecast simply changes the type that MATLAB uses to interpret the underlying byte values.

Alternatively you could simply use int64

>> int64(s)
ans =
    4026500000

to convert data whilst attempting to keep the same value.


Aside: sum is a built-in MATLAB function. It is not recommended that you call a variable sum as you will overwrite the built-in MATLAB function.

Upvotes: 4

Related Questions