convertNumber

Java进制转换
本文介绍Java中不同进制之间的转换方法,包括十进制与其他进制间的相互转换。通过Integer类的方法如toBinaryString(), toOctalString(), toHexString()等实现二进制、八进制、十六进制到十进制的转换。
  1. 十进制转成十六进制:   
  2.   
  3. Integer.toHexString(int  i)   
  4.   
  5. 十进制转成八进制   
  6.   
  7. Integer.toOctalString(int  i)   
  8.   
  9. 十进制转成二进制   
  10.   
  11. Integer.toBinaryString(int  i)   
  12.   
  13. 十六进制转成十进制   
  14.   
  15. Integer.valueOf("FFFF" , 16 ).toString()   
  16.   
  17. 八进制转成十进制   
  18.   
  19. Integer.valueOf("876" , 8 ).toString()   
  20.   
  21. 二进制转十进制   
  22.   
  23. Integer.valueOf("0101" , 2 ).toString()   
  24.   
  25.   
  26.   
  27. 有什么方法可以直接将2 , 8 , 16 进制直接转换为 10 进制的吗?   
  28.   
  29. java.lang.Integer类   
  30.   
  31. parseInt(String s, int  radix)   
  32.   
  33. 使用第二个参数指定的基数,将字符串参数解析为有符号的整数。   
  34.   
  35. examples from jdk:   
  36.   
  37. parseInt("0"10 ) returns  0    
  38.   
  39. parseInt("473"10 ) returns  473    
  40.   
  41. parseInt("-0"10 ) returns  0    
  42.   
  43. parseInt("-FF"16 ) returns - 255    
  44.   
  45. parseInt("1100110"2 ) returns  102    
  46.   
  47. parseInt("2147483647"10 ) returns  2147483647    
  48.   
  49. parseInt("-2147483648"10 ) returns - 2147483648    
  50.   
  51. parseInt("2147483648"10throws  a NumberFormatException   
  52.   
  53. parseInt("99" , throws  a NumberFormatException   
  54.   
  55. parseInt("Kona"10throws  a NumberFormatException   
  56.   
  57. parseInt("Kona"27 ) returns  411787    
  58.   
  59.   
  60.   
  61. 进制转换如何写(二,八,十六)不用算法   
  62.   
  63. Integer.toBinaryString   
  64.   
  65. Integer.toOctalString   
  66.   
  67. Integer.toHexString   
  68.   
  69.   
  70.   
  71.   
  72.   
  73. 例二   
  74.   
  75.   
  76.   
  77. public   class  Test{   
  78.   
  79. public   static   void  main(String args[]){   
  80.   
  81.   
  82.   
  83. int  i= 100 ;   
  84.   
  85. String binStr=Integer.toBinaryString(i);   
  86.   
  87. String otcStr=Integer.toOctalString(i);   
  88.   
  89. String hexStr=Integer.toHexString(i);   
  90.   
  91. System.out.println(binStr);   
  92.   
  93.   
  94.   
  95. }   
  96.   
  97.   
  98.   
  99.   
  100.   
  101.   
  102.   
  103. 例二   
  104.   
  105. public   class  TestStringFormat {   
  106.   
  107. public   static   void  main(String[] args) {   
  108.   
  109. if  (args.length ==  0 ) {   
  110.   
  111. System.out.println("usage: java TestStringFormat <a number>" );   
  112.   
  113. System.exit(0 );   
  114.   
  115. }   
  116.   
  117.   
  118.   
  119. Integer factor = Integer.valueOf(args[0 ]);   
  120.   
  121.   
  122.   
  123. String s;   
  124.   
  125.   
  126.   
  127. s = String.format("%d" , factor);   
  128.   
  129. System.out.println(s);   
  130.   
  131. s = String.format("%x" , factor);   
  132.   
  133. System.out.println(s);   
  134.   
  135. s = String.format("%o" , factor);   
  136.   
  137. System.out.println(s);   
  138.   
  139. }   
  140.   
  141. }   
  142.   
  143.   
  144.   
  145.   
  146.   
  147.   
  148.   
  149. 其他方法:   
  150.   
  151.   
  152.   
  153. Integer.toHexString(你的10 进制数);   
  154.   
  155. 例如   
  156.   
  157. String temp = Integer.toHexString(75 );   
  158.   
  159. 输出temp就为 4b   
  160.   
  161.   
  162.   
  163.   
  164.   
  165.   
  166.   
  167. //输入一个10进制数字并把它转换成16进制    
  168.   
  169. import  java.io.*;   
  170.   
  171. public   class  toHex{   
  172.   
  173.   
  174.   
  175. public   static   void  main(String[]args){   
  176.   
  177.   
  178.   
  179. int  input; //存放输入数据    
  180.   
  181. //创建输入字符串的实例    
  182.   
  183. BufferedReader strin=new  BufferedReader( new  InputStreamReader(System.in));   
  184.   
  185. System.out.println("请输入一个的整数:" );   
  186.   
  187. String x=null ;   
  188.   
  189. try {   
  190.   
  191. x=strin.readLine();   
  192.   
  193. }catch (IOException ex){   
  194.   
  195. ex.printStackTrace();   
  196.   
  197. }   
  198.   
  199. input=Integer.parseInt(x);   
  200.   
  201. System.out.println ("你输入的数字是:" +input); //输出从键盘接收到的数字    
  202.   
  203.   
  204.   
  205. System.out.println ("它的16进制是:" +Integer.toHexString(input)); //用toHexString把10进制转换成16进制    
  206.   
  207. }   
  208.   
  209. }  
import router from '@ohos.router'; import promptAction from '@ohos.promptAction'; import data_preferences from '@ohos.data.preferences'; @Entry @Component struct NumberBaseConverterPage { @State inputNumber: string = '10'; // 提供默认值 @State inputBase: number = 10; @State binaryResult: string = '等待计算...'; @State octalResult: string = '等待计算...'; @State decimalResult: string = '等待计算...'; @State hexResult: string = '等待计算...'; @State base64Result: string = '等待计算...'; @State customBase: number = 16; @State customResult: string = '等待计算...'; @State historyList: string[] = []; @State showHistory: boolean = false; // 可选的进制列表 private baseOptions: string[] = ['2', '8', '10', '16']; private customBaseOptions: string[] = ['2','3','4','5','6','7','8','9','10', '11','12','13','14','15','16','32','36']; aboutToAppear() { this.loadHistory(); // 页面加载时自动计算默认值的转换结果 setTimeout(() => { this.convertNumber(); }, 100); } convertNumber() { console.log('开始转换: ' + this.inputNumber + ' (base: ' + this.inputBase + ')'); if (!this.inputNumber) { promptAction.showToast({ message: '请输入要转换的数字' }); console.log('未输入数字'); return; } try { // 先尝试直接转换,再进行严格验证 let decimalValue: number = parseInt(this.inputNumber, this.inputBase); if (isNaN(decimalValue)) { // 如果直接转换失败,进行严格验证找出问题 if (!this.isValidNumber(this.inputNumber, this.inputBase)) { throw new Error('输入的数字与所选进制不兼容'); } throw new Error('无效的数字或进制'); } console.log('十进制值: ' + decimalValue); // 计算各种进制结果 // 使用setTimeout确保在主线程上更新状态 setTimeout(() => { this.binaryResult = decimalValue.toString(2); this.octalResult = decimalValue.toString(8); this.decimalResult = decimalValue.toString(10); this.hexResult = decimalValue.toString(16).toUpperCase(); this.base64Result = this.convertToBase64(this.inputNumber); this.customResult = decimalValue.toString(this.customBase); console.log('转换结果: binary=' + this.binaryResult + ', octal=' + this.octalResult + ', decimal=' + this.decimalResult + ', hex=' + this.hexResult + ', base64=' + this.base64Result + ', custom=' + this.customResult); promptAction.showToast({ message: '转换完成' }); }, 0); this.saveToHistory(this.inputNumber, this.inputBase); } catch (error) { console.error('转换错误:', error); promptAction.showToast({ message: error.message || '转换错误' }); // 出错时设置为错误信息,而不是保持原样 setTimeout(() => { this.binaryResult = '转换失败'; this.octalResult = '转换失败'; this.decimalResult = '转换失败'; this.hexResult = '转换失败'; this.base64Result = '转换失败'; this.customResult = '转换失败'; }, 0); } } // 改进的Base64转换方法 private convertToBase64(str: string): string { try { // 尝试使用简化的方式处理数字到Base64的转换 if (/^\d+$/.test(str)) { const num = parseInt(str); if (!isNaN(num)) { const base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; let result = ''; let i = 0; let bytes = new ArrayBuffer(4); let view = new DataView(bytes); view.setUint32(0, num); while (i < 4) { const char1 = view.getUint8(i++); const char2 = i < 4 ? view.getUint8(i++) : 0; const char3 = i < 4 ? view.getUint8(i++) : 0; const enc1 = char1 >> 2; const enc2 = ((char1 & 3) << 4) | (char2 >> 4); const enc3 = ((char2 & 15) << 2) | (char3 >> 6); const enc4 = char3 & 63; result += base64chars.charAt(enc1) + base64chars.charAt(enc2); result += i > 3 ? '==' : i > 2 ? '=' : base64chars.charAt(enc3); result += i > 2 ? '' : base64chars.charAt(enc4); } return result; } } // 使用原始的Base64实现 const base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; let result = ''; let i = 0; let pad = 0; let char1: number, char2: number, char3: number; let enc1: number, enc2: number, enc3: number, enc4: number; while (i < str.length) { char1 = str.charCodeAt(i++) || 0; char2 = i < str.length ? str.charCodeAt(i++) : 0; char3 = i < str.length ? str.charCodeAt(i++) : 0; pad = [0, 2, 1][str.length - i + 1] || 0; enc1 = char1 >> 2; enc2 = ((char1 & 3) << 4) | (char2 >> 4); enc3 = ((char2 & 15) << 2) | (char3 >> 6); enc4 = char3 & 63; result += base64chars.charAt(enc1) + base64chars.charAt(enc2); result += pad >= 2 ? '=' : base64chars.charAt(enc3); result += pad >= 1 ? '=' : base64chars.charAt(enc4); } return result; } catch (error) { console.error('Base64转换错误:', error); return '转换失败'; } } async loadHistory() { try { let preferences = await data_preferences.getPreferences(getContext(this), 'NumberBaseHistory'); let history = await preferences.get('history', '[]'); this.historyList = JSON.parse(history.toString()); } catch (error) { console.error('Failed to load history'); } } async saveToHistory(number: string, base: number) { const record = `${number} (${base}进制)`; if (!number || this.historyList.includes(record)) { return; } try { this.historyList.unshift(record); if (this.historyList.length > 10) { this.historyList = this.historyList.slice(0, 10); } let preferences = await data_preferences.getPreferences(getContext(this), 'NumberBaseHistory'); await preferences.put('history', JSON.stringify(this.historyList)); await preferences.flush(); } catch (error) { console.error('Failed to save history'); } } // 验证输入数字是否与选择的进制兼容 private isValidNumber(number: string, base: number): boolean { // 处理特殊情况:空字符串 if (!number) return false; // 定义每个进制的有效字符 let validChars: string; switch (base) { case 2: validChars = '01'; break; case 8: validChars = '01234567'; break; case 10: validChars = '0123456789'; break; case 16: validChars = '0123456789ABCDEFabcdef'; break; default: // 对于其他进制,生成有效的字符集 validChars = ''; for (let i = 0; i < base; i++) { if (i < 10) { validChars += i.toString(); } else { validChars += String.fromCharCode(55 + i); // 'A'-'Z' validChars += String.fromCharCode(87 + i); // 'a'-'z' } } } // 检查每个字符是否有效 for (let char of number) { if (!validChars.includes(char)) { console.log('无效字符: ' + char + ' 在进制: ' + base); return false; } } return true; } // 简单的Base64实现(原方法,保留作为参考) private simpleBase64(str: string): string { const base64chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; let result = ''; let i = 0; let char1: number, char2: number, char3: number; let enc1: number, enc2: number, enc3: number, enc4: number; while (i < str.length) { char1 = str.charCodeAt(i++); char2 = str.charCodeAt(i++); char3 = str.charCodeAt(i++); enc1 = char1 >> 2; enc2 = ((char1 & 3) << 4) | (char2 >> 4); enc3 = ((char2 & 15) << 2) | (char3 >> 6); enc4 = char3 & 63; if (isNaN(char2)) { enc3 = enc4 = 64; } else if (isNaN(char3)) { enc4 = 64; } result += base64chars.charAt(enc1) + base64chars.charAt(enc2) + base64chars.charAt(enc3) + base64chars.charAt(enc4); } return result || '不支持该转换'; } build() { Scroll() { Column() { // 导航栏 Row() { Text('数字进制转换') .fontSize(20) .fontWeight(FontWeight.Bold) Blank() Button('返回') .fontSize(16) .fontColor(Color.White) .backgroundColor('#0D6EFD') .borderRadius(8) .height(36) .onClick(() => { router.back(); }) } .width('100%') .padding(10) .justifyContent(FlexAlign.Start) .alignItems(VerticalAlign.Center) // 输入区域 Column() { Text('输入数字:') .fontSize(16) .alignSelf(ItemAlign.Start) .margin({ top: 20, bottom: 10 }) Row() { TextInput({ text: this.inputNumber }) .width('60%') .height(50) .backgroundColor('#ff154364') .fontColor(Color.White) .borderRadius(8) .fontSize(16) .padding(10) .onChange((value: string) => { this.inputNumber = value; }) // 使用TextPicker替代Picker TextPicker({ range: this.baseOptions }) .width('30%') .height(50) .margin({ left: 10 }) .onChange((value: string | string[], index: number | number[]) => { const selectedValue = typeof value === 'string' ? value : value[0]; this.inputBase = parseInt(selectedValue); }) } .width('100%') Row() { Button(this.showHistory ? '隐藏历史' : '显示历史') .width('100%') .height(40) .margin({ top: 10 }) .onClick(() => { this.showHistory = !this.showHistory; }) } .width('100%') } .width('90%') .padding(10) // 历史记录 if (this.showHistory) { Column() { Text('历史记录') .fontSize(16) .fontWeight(FontWeight.Bold) .alignSelf(ItemAlign.Start) .margin({ top: 10, bottom: 5 }) List() { ForEach(this.historyList, (item: string) => { ListItem() { Row() { Text(item) .fontSize(14) .width('70%') Button('使用') .width('25%') .height(30) .fontSize(14) .onClick(() => { const match = item.match(/(.*) \((\d+)进制\)/); if (match) { this.inputNumber = match[1]; this.inputBase = parseInt(match[2]); } this.showHistory = false; }) } .width('100%') .padding(5) } }) } .width('100%') .height(150) .backgroundColor('#ff154364') .borderRadius(8) .padding(5) .scrollBar(BarState.Auto) } .width('90%') } // 结果区域 Column() { Text('转换结果') .fontSize(18) .fontWeight(FontWeight.Bold) .alignSelf(ItemAlign.Start) .margin({ top: 20, bottom: 10 }) this.buildResultItem('二进制:', this.binaryResult) this.buildResultItem('八进制:', this.octalResult) this.buildResultItem('十进制:', this.decimalResult) this.buildResultItem('十六进制:', this.hexResult) this.buildResultItem('Base64:', this.base64Result) Row() { // 使用TextPicker替代Picker TextPicker({ range: this.customBaseOptions }) .width('40%') .height(50) .onChange((value: string | string[], index: number | number[]) => { const selectedValue = typeof value === 'string' ? value : value[0]; this.customBase = parseInt(selectedValue); if (this.inputNumber) { this.convertNumber(); } }) Text(this.customResult || '等待计算...') .width('60%') .fontSize(16) .margin({ left: 10 }) } .width('100%') .padding(10) .margin({ top: 5, bottom: 5 }) .borderRadius(8) .backgroundColor('#ff154364') Button('开始转换') .width('100%') .height(50) .margin({ top: 20 }) .onClick(() => { this.convertNumber(); }) } .width('90%') .padding(10) .margin({ top: 10 }) .backgroundColor('#ff154364') .borderRadius(10) } .width('100%') .height('100%') .backgroundColor('#0D6EFD20') } .width('100%') .height('100%') } @Builder buildResultItem(label: string, value: string) { Row() { Text(label) .width('40%') .fontSize(16) .fontWeight(FontWeight.Bold) Text(value || '等待计算...') .width('60%') .fontSize(16) .fontColor(Color.White) } .width('100%') .padding(10) .margin({ top: 5, bottom: 5 }) .borderRadius(8) .backgroundColor('#ff154364') } }为什么此功能实现转换,但转换结果却不显示更新
09-27
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>进制转换小工具</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } body { background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%); min-height: 100vh; display: flex; justify-content: center; align-items: center; padding: 20px; } .container { background-color: rgba(255, 255, 255, 0.9); border-radius: 20px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2); width: 100%; max-width: 800px; padding: 30px; animation: fadeIn 0.5s ease-out; } @keyframes fadeIn { from { opacity: 0; transform: translateY(20px); } to { opacity: 1; transform: translateY(0); } } h1 { text-align: center; color: #333; margin-bottom: 10px; font-size: 2.2rem; } .subtitle { text-align: center; color: #666; margin-bottom: 30px; font-size: 1rem; } .input-section { margin-bottom: 25px; } .input-group { margin-bottom: 15px; } label { display: block; margin-bottom: 8px; font-weight: 600; color: #444; } input, select { width: 100%; padding: 12px 15px; border: 2px solid #ddd; border-radius: 10px; font-size: 16px; transition: all 0.3s; } input:focus, select:focus { border-color: #6a11cb; outline: none; box-shadow: 0 0 0 3px rgba(106, 17, 203, 0.2); } .convert-btn { background: linear-gradient(to right, #6a11cb, #2575fc); color: white; border: none; padding: 14px 20px; border-radius: 10px; font-size: 16px; font-weight: 600; cursor: pointer; width: 100%; transition: all 0.3s; margin-top: 10px; } .convert-btn:hover { transform: translateY(-2px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.2); } .convert-btn:active { transform: translateY(0); } .results { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 15px; margin-top: 25px; } .result-box { background-color: #f8f9fa; border-radius: 10px; padding: 15px; box-shadow: 0 3px 10px rgba(0, 0, 0, 0.05); transition: all 0.3s; } .result-box:hover { transform: translateY(-3px); box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1); } .result-title { font-size: 14px; color: #666; margin-bottom: 8px; font-weight: 600; } .result-value { font-size: 18px; font-weight: 700; color: #333; word-break: break-all; } .binary { border-left: 4px solid #ff6b6b; } .decimal { border-left: 4px solid #4ecdc4; } .octal { border-left: 4px solid #45b7d1; } .hex { border-left: 4px solid #ffa502; } .error-message { color: #e74c3c; text-align: center; margin-top: 15px; font-weight: 600; display: none; } .footer { text-align: center; margin-top: 30px; color: #777; font-size: 14px; } @media (max-width: 600px) { .container { padding: 20px; } h1 { font-size: 1.8rem; } .results { grid-template-columns: 1fr; } } </style> </head> <body> <div class="container"> <h1>进制转换小工具</h1> <p class="subtitle">支持十进制、二进制、八进制和十六进制之间的相互转换</p> <div class="input-section"> <div class="input-group"> <label for="inputValue">输入数值:</label> <input type="text" id="inputValue" placeholder="请输入要转换的数值"> </div> <div class="input-group"> <label for="inputBase">选择输入数值的进制:</label> <select id="inputBase"> <option value="10">十进制</option> <option value="2">二进制</option> <option value="8">八进制</option> <option value="16">十六进制</option> </select> </div> <button class="convert-btn" id="convertBtn">转换</button> </div> <div class="error-message" id="errorMessage"></div> <div class="results"> <div class="result-box binary"> <div class="result-title">二进制</div> <div class="result-value" id="binaryResult">-</div> </div> <div class="result-box decimal"> <div class="result-title">十进制</div> <div class="result-value" id="decimalResult">-</div> </div> <div class="result-box octal"> <div class="result-title">八进制</div> <div class="result-value" id="octalResult">-</div> </div> <div class="result-box hex"> <div class="result-title">十六进制</div> <div class="result-value" id="hexResult">-</div> </div> </div> <div class="footer"> <p>计算机作业 - 进制转换工具 | 使用说明:输入数值并选择其进制,点击转换按钮查看结果</p> </div> </div> <script> document.addEventListener('DOMContentLoaded', function() { const convertBtn = document.getElementById('convertBtn'); const inputValue = document.getElementById('inputValue'); const inputBase = document.getElementById('inputBase'); const errorMessage = document.getElementById('errorMessage'); const binaryResult = document.getElementById('binaryResult'); const decimalResult = document.getElementById('decimalResult'); const octalResult = document.getElementById('octalResult'); const hexResult = document.getElementById('hexResult'); convertBtn.addEventListener('click', convertNumber); function convertNumber() { // 隐藏错误消息 errorMessage.style.display = 'none'; const value = inputValue.value.trim(); const base = parseInt(inputBase.value); // 验证输入 if (!value) { showError('请输入要转换的数值'); return; } try { // 将输入值转换为十进制 let decimalValue; if (base === 10) { decimalValue = parseInt(value); if (isNaN(decimalValue)) { showError('请输入有效的十进制数值'); return; } } else if (base === 2) { // 验证二进制输入 if (!/^[01]+$/.test(value)) { showError('二进制只能包含0和1'); return; } decimalValue = parseInt(value, 2); } else if (base === 8) { // 验证八进制输入 if (!/^[0-7]+$/.test(value)) { showError('八进制只能包含0-7'); return; } decimalValue = parseInt(value, 8); } else if (base === 16) { // 验证十六进制输入 if (!/^[0-9A-Fa-f]+$/.test(value)) { showError('十六进制只能包含0-9和A-F'); return; } decimalValue = parseInt(value, 16); } // 检查转换结果是否有效 if (isNaN(decimalValue)) { showError('无法转换输入的数值,请检查格式是否正确'); return; } // 转换为各种进制并显示结果 binaryResult.textContent = decimalValue.toString(2); decimalResult.textContent = decimalValue.toString(10); octalResult.textContent = decimalValue.toString(8); hexResult.textContent = decimalValue.toString(16).toUpperCase(); } catch (error) { showError('转换过程中发生错误: ' + error.message); } } function showError(message) { errorMessage.textContent = message; errorMessage.style.display = 'block'; // 清空结果 binaryResult.textContent = '-'; decimalResult.textContent = '-'; octalResult.textContent = '-'; hexResult.textContent = '-'; } // 示例:初始显示一个转换示例 inputValue.value = '255'; convertNumber(); }); </script> </body> </html>
最新发布
10-14
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值