diff --git a/util/bits.go b/util/bits.go new file mode 100644 index 0000000..115560a --- /dev/null +++ b/util/bits.go @@ -0,0 +1,6 @@ +package util + +// Tells if bit is set in given byte +func IsSet(n byte, bitN int) bool { + return n&byte(1<> 25 //00000000 00000000 00000000 01101010 - bytes = append(bytes, byte(shifted)) - } + // skip 4 0`ed bits + gInt = gInt << 4 + + // int32 == 4 bytes + for i := 0; i < 32/8; i++ { + // get first 7 bits + first7Bits := gInt & first7BitsMask - return bytes + // shift captured bits to the beginning + first7Bits = first7Bits >> (3*8 + 1) + + b := byte(first7Bits) + synchsafeIBytes = append(synchsafeIBytes, b) + + // prepare next 7 bits for the next iteration + gInt = gInt << 7 + } + return synchsafeIBytes } // Converts given bytes into string, ignoring the first 31 non-printable ASCII characters. diff --git a/util/conversion_test.go b/util/conversion_test.go index 9736e0b..01326b0 100644 --- a/util/conversion_test.go +++ b/util/conversion_test.go @@ -25,13 +25,23 @@ func TestDecodeText(t *testing.T) { } } -// func TestIntToBytesFirstBitZeroed(t *testing.T) { -// var testint uint32 = 123456 +func TestIntToBytesSynchsafe(t *testing.T) { + testInts := []uint32{ + 1234, + 12, + 1, + 0, + 99999, + 87654321, + } + + for _, testInt := range testInts { + synchSafeBytes := IntToBytesSynchsafe(testInt) -// intbytes := IntToBytesFirstBitZeroed(testint) + synchsafeInt := BytesToIntSynchsafe(synchSafeBytes) -// if BytesToIntIgnoreFirstBit(intbytes) != testint { -// t.Errorf("IntToBytesFirstBitZeroed failed: expected to get %v; got %v", -// testint, BytesToIntIgnoreFirstBit(intbytes)) -// } -// } + if synchsafeInt != testInt { + t.Errorf("BytesToIntSynchsafe failed: expected to get %d; got %d", testInt, synchsafeInt) + } + } +}