簡體   English   中英

如何在Java中將十六進制字符串轉換為八進制字符串

[英]How to convert hex string to octal string in java

我正在將字符串轉換為十六進制字符串,我想將其轉換為八進制字符串

我正在做如下

String s="I found the reason 2 days ago i was too bussy to update you.The problem was that the UDHL was missing. I should have added 06 at the beginning.  it all works fine.For some reason I thought kannel adds this by itself (not very difficult...), but now I know it doesn't...";


String hex = String.format("%040x", new BigInteger(1, s.getBytes("UTF-8")));    

輸出是

4920666f756e642074686520726561736f6e203220646179732061676f20692077617320746f6f20627573737920746f2075706461746520796f752e5468652070726f626c656d20776173207468617420746865205544484c20776173206d697373696e672e20492073686f756c6420686176652061646465642030362061742074686520626567696e6e696e672e2020697420616c6c20776f726b732066696e652e466f7220736f6d6520726561736f6e20492074686f75676874206b616e6e656c2061646473207468697320627920697473656c6620286e6f74207665727920646966666963756c742e2e2e292c20627574206e6f772049206b6e6f7720697420646f65736e27742e2e2e

我需要將十六進制轉換為八進制字符串。 我嘗試過這樣

String octal = Integer.toOctalString(Integer.parseInt(hex,16));

但是正如預期的那樣,它給了我數字格式例外,因為十六進制字符串中包含一些字符。

我想知道如何將十六進制字符串轉換為八進制字符串。

根據評論中的討論,您希望將每個字節分別轉換為八進制:

String s     = "My string to convert";
byte[] bytes = s.getBytes("UTF-8");

for (byte b : bytes) {
    String octalValue = Integer.toString(b, 8);

    // Do whatever
}

問題在於,您的輸入( String hex )太大了,無法存儲在單個整數中。

3個十六進制數字對應4個八進制數字。 因此,將您的輸入字符串分成三位數,使用您已經弄清楚的轉換並將輸出連接起來。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM