2011-09-28 62 views
0

爲十進制用於分配我必須寫一個程序,將在8個字符的字符串(十六進制),然後將其轉換爲基座10我不允許使用任何外的類做這個。我很確定我的工作正常......只有正數。我的問題是如何顯示負數。 一個例子是,FFFFFFFA應打印出-6 這是到目前爲止我的代碼轉換32點比特的十六進制在Java

package hexconverter; 

import java.util.*; 

/** 
* 
* @author Steven 
*/ 
public class Main { 

    Scanner scanner = new Scanner(System.in); 

    public void doWork() { 



     System.err.println("Please enter the internal representation: "); 
     String hex; 
     hex = scanner.next(); 
     hex = hex.toUpperCase(); 

     long count = 1; 
     long ans = 0; 

     for (int i = 7; i >= 0; i--) { 
      Character c = hex.charAt(i); 

      if (c != '1' && c != '2' && c != '3' && c != '4' && c != '5' && c != '6' && c != '7' && c != '8' && c != '9') { 
       int num = fixLetters(c); 
       ans = ans + (num * count); 
       count = count * 16; 
      } else { 

       String s = c.toString(c); 
       long num = Integer.parseInt(s); 
       ans = ans + (num * count); 
       count = count * 16; 
      } 
     } 

     if (ans > 2147483647) { 
      System.out.println("is negative"); 


     } else { 
      System.out.println(ans); 
     } 
    } 

    public int fixLetters(Character c) { 
     if (c.equals('A')) { 
      return 10; 
     } else if (c.equals('B')) { 
      return 11; 
     } else if (c.equals('C')) { 
      return 12; 
     } else if (c.equals('D')) { 
      return 13; 
     } else if (c.equals('E')) { 
      return 14; 
     } else if (c.equals('F')) { 
      return 15; 
     } else { 
      return 0; 
     } 

    } 

    public static void main(String[] args) { 
     // TODO code application logic here 
     Main a = new Main(); 
     a.doWork(); 
    } 
} 

我想我的一個負整數測試是正確的......因爲這是最高值的32位可以容納,任何超過這將是一個溢出,所以這意味着它應該是負面的。 從這裏我不知道如何去做這件事。任何指針或提示將不勝感激。如果沒有辦法在數學上做到這一點,我覺得我必須將十六進制轉換爲二進制,然後執行二進制補碼,但我不知道從哪裏開始。

在此先感謝

+0

因爲一半是積極的,一半是消極的權利?謝謝,我錯過了! – Cheesegraterr

+1

@Hovercraft完整的鰻魚:我上次檢查時,'2^31 = 2147483648' – Mysticial

+0

sh!t,你說得對。 :(我會盡快刪除我的評論。對不起! –

回答

2

在32位2的補碼的二進制表示,負的值正好是比在無符號的表示相同的位模式的值小於2^32。你已經確定這個數字可能是負數;所有剩下要做的就是減去2^32.

當然,2^32(十進制中的4294967296或十六進制中的0x100000000)是不能用Java的「int」類型表示的值,我需要使用一個「長」:

if (ans > 2147483647) { 
    // System.out.println("is negative"); 
    ans = ans - 0x100000000L; 
    System.out.println(ans); 
} else { 
3

如果號碼是代碼中的負(> 2147483647),僅僅從它減去2^32(4294967296)。然後打印出來。

if (ans > 2147483647) { 
     System.out.println(ans - 4294967296L); 
    } else { 
     System.out.println(ans); 
    } 
+0

謝謝!我不相信我沒有看到我自己似乎在完美地工作。 – Cheesegraterr