Skip to content

Instantly share code, notes, and snippets.

@koji-k
Created May 8, 2017 11:47
Show Gist options
  • Save koji-k/c145eb8dcde4fbbb7039f0dea2c4c688 to your computer and use it in GitHub Desktop.
Save koji-k/c145eb8dcde4fbbb7039f0dea2c4c688 to your computer and use it in GitHub Desktop.
16進数(Byte)から2進数の文字列を得る
class Bin {
Integer maxBit = 8
Byte b
String binaryString
String latestPaddingPrefix
static of (Integer b) {
new Bin(b as Byte)
}
private Bin(Byte b) {
this.b = b
binaryString = toBinaryString(b)
latestPaddingPrefix = '0'
}
def shiftL(Integer operand) {
b = b << operand
binaryString = toBinaryString(b)
latestPaddingPrefix = '0'
this
}
def shiftR(Integer operand) {
b = b >> operand
binaryString = toBinaryString(b)
latestPaddingPrefix = binaryString[0] == '1' ? '1' : '0'
this
}
String toBinaryString(Byte b) {
Integer.toBinaryString(b)
}
String normalize() {
if (binaryString.length() > maxBit) {
binaryString[-maxBit..-1]
} else {
binaryString.padLeft(maxBit, latestPaddingPrefix)
}
}
}
assert "00010101" == Bin.of(0x15).normalize()
assert "00101010" == Bin.of(0x15).shiftL(1).normalize()
assert "01010100" == Bin.of(0x15).shiftL(2).normalize()
assert "10100011" == Bin.of(0xA3).normalize()
assert "11010001" == Bin.of(0xA3).shiftR(1).normalize()
assert "11101000" == Bin.of(0xA3).shiftR(2).normalize()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment