将2的补码转换为十进制 [英] Convert 2's complement to decimal

查看:121
本文介绍了将2的补码转换为十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在c#中工作,我有一个字节代表数字的2的补码值,我需要将其转换为十进制。该字节来自加速度计LIS302DL。提前谢谢!

I`m working in c# and i have a byte representing the 2's complement value of a number and i need to convert it to decimal. This byte comes from an accelerometer LIS302DL. Thanks in advance!

推荐答案

表示2的补码的字节可能只意味着一件事:隐含类型是有符号字节(或者这不是2的补码)。您可以通过赋值将其直接转换/转换为int变量或任何其他更宽的有符号整数类型。目前尚不清楚十进制是什么意思。在这是一个字符串,您可以使用 sprintf ToString 将其转换为字符串。



-SA
A "byte representing the 2's complement" might mean only one thing: the implied type is signed byte (or this is not 2's complement). You can cast/convert it directly to a variable of int or any other wider signed integer type, implicitly, by assignment. It's not clear what to you mean by 'decimal'. In this is a string, you can convert it to string using sprintf or ToString.

—SA


我知道这个问题已经老了但是很糟糕,下一个人的例子没有受到伤害。数学很简单。



I know the question is old but heck, an example for the next guy doesn't hurt. The math is quite simple for this.

public static int ConvertTwosComplementByteToInteger(byte rawValue)
{
    // If a positive value, return it
    if ((rawValue & 0x80) == 0)
    {
        return rawValue;
    }

    // Otherwise perform the 2's complement math on the value
    return (byte)(~(rawValue - 0x01)) * -1;
}


这篇关于将2的补码转换为十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆