《Java语言程序设计(基础篇)》(第10版 梁勇 著)第十七章练习题答案

catch (IOException ex) { ex.printStackTrace(); } }); }

/** Convert a hex string to bit string */ public static String toBits(String hex) { String s = \;

for (int i = 0; i < hex.length(); i++) { char hexChar = hex.charAt(i); switch (hexChar) {

case '0': s += \; break; case '1': s += \; break; case '2': s += \; break; case '3': s += \; break; case '4': s += \; break; case '5': s += \; break; case '6': s += \; break; case '7': s += \; break; case '8': s += \; break; case '9': s += \; break; case 'A': s += \; break; case 'B': s += \; break; case 'C': s += \; break; case 'D': s += \; break; case 'E': s += \; break; case 'F': s += \; break; } }

return s; }

public static int hexCharToDecimal(char ch) {

ch = Character.toUpperCase(ch); // Change it to uppercase if (ch >= 'A' && ch <= 'F') return 10 + ch - 'A';

else // ch is '0', '1', ..., or '9' return ch - '0'; }

/** Convert the 8-bit string to a 2-digit hex number */ public static String getHex(String bitString) {

// Get the first half hex number

int value = (bitString.charAt(0) - '0') * 8 + (bitString.charAt(1) - '0') * 4 + (bitString.charAt(2) - '0') * 2 + (bitString.charAt(3) - '0') * 1;

String result = \ + toHexChar(value);

// Get the second half hex number

value = (bitString.charAt(4) - '0') * 8 + (bitString.charAt(5) - '0') * 4 + (bitString.charAt(6) - '0') * 2 + (bitString.charAt(7) - '0') * 1;

return result + toHexChar(value); }

/** Convert an integer to a single hex digit in a character */ public static char toHexChar(int hexValue) { if (hexValue <= 9 && hexValue >= 0) return (char)(hexValue + '0');

else // hexValue <= 15 && hexValue >= 10 return (char)(hexValue - 10 + 'A'); }

public static String getBits(int value) { String result = \;

int mask = 1;

for (int i = 7; i >= 0; i--) { int temp = value >> i; int bit = temp & mask; result = result + bit; }

return result; }

public static class BitOutputStream { private FileOutputStream output; private int value; private int count = 0;

private int mask = 1; // The bits are all zeros except the last one

public BitOutputStream(File file) throws IOException {

output = new FileOutputStream(file); }

public void writeBit(char bit) throws IOException { count++;

value = value << 1;

if (bit == '1') value = value | mask;

if (count == 8) { output.write(value); count = 0; } }

public void writeBit(String bitString) throws IOException { for (int i = 0; i < bitString.length(); i++) writeBit(bitString.charAt(i)); }

/** Write the last byte and close the stream. If the last byte is not full, right-shfit with zeros */

public void close() throws IOException { if (count > 0) {

value = value << (8 - count); output.write(value); }

output.close(); } } /**

* The main method is only needed for the IDE with limited * JavaFX support. Not needed for running from the command line. */

public static void main(String[] args) { launch(args); } }

联系客服:779662525#qq.com(#替换为@) 苏ICP备20003344号-4