【问题标题】:printing scalar as int32 in Matlab在 Matlab 中将标量打印为 int32
【发布时间】:2018-04-10 13:07:32
【问题描述】:

我正在尝试打印标量,就像它是 int32 一样。也就是说,如果我有2532063508,如果我把它写成 4 个字节并读为 int32,我会读到-1762903788

在 Matlab 中使用 int32 函数不起作用,因为它的工作方式是,[-2^31,2^31-1] 范围之外的值映射到最近的端点。

所以我尝试使用typecast

typecast(uint32(2532063508), 'int32')

效果很好,但是如果我写例如-1 那里,uint32() 返回 0 所以它失败了。

附:我希望它也适用于有符号整数作为输入,也就是说,对于 -1 它应该返回 -1

有什么建议吗?

【问题讨论】:

    标签: matlab type-conversion integer signed


    【解决方案1】:

    您可以在int64 中进行计算,然后转换为uint32

    f = @(x)typecast(uint32(mod(int64(x),int64(2)^32)),'int32');
    

    或者

    function y = f(x)
        y = typecast(uint32(mod(int64(x),int64(2)^32)),'int32');
    end
    

    所以f([-1, 2532063508]) 返回[-1, -1762903788]

    【讨论】:

    • 不确定我是否得到它,你能把它写成 y=f(x) 形式,我输入 x=[-1, 2532063508] and it would return [-1, -1762903788]` 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多