Skip to content

Commit

Permalink
Refactor ConvertBitsToBytes function
Browse files Browse the repository at this point in the history
  • Loading branch information
J3imip authored Dec 30, 2024
1 parent a90a4f8 commit 9b65208
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions internal/utils/asn1_operations.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,19 @@ import (

func ConvertBitsToBytes(data []byte, numBits int) ([]byte, error) {
numBytes := (numBits + 7) / 8
if len(data) < numBytes {
return nil, fmt.Errorf("data is too short, requires at least %d bytes", numBytes)
result := make([]byte, numBytes)

startIndex := len(data) - numBytes
if startIndex < 0 {
startIndex = 0
}

result := make([]byte, numBytes)
copy(result, data[:numBytes])
copy(result[max(0, numBytes-len(data)):], data[startIndex:])

remainingBits := numBits % 8
if remainingBits != 0 {
mask := byte(0xFF << (8 - remainingBits))
result[numBytes-1] &= mask
mask := byte(0xFF >> (8 - remainingBits))
result[0] &= mask
}

return result, nil
Expand Down

0 comments on commit 9b65208

Please sign in to comment.