Bytes returns the number serialized as a little endian with a sign bit. Example encodings: 127 -> [0x7f] -127 -> [0xff] 128 -> [0x80 0x00] -128 -> [0x80 0x80] 129 -> [0x81 0x00] -129 -> [0x81 0x80] 256 -> [0x00 0x01] -256 -> [0x00 0x81] 32767 -> [0xff 0x7f] -32767 ->
()
| 103 | // 32768 -> [0x00 0x80 0x00] |
| 104 | // -32768 -> [0x00 0x80 0x80] |
| 105 | func (n scriptNum) Bytes() []byte { |
| 106 | // Zero encodes as an empty byte slice. |
| 107 | if n == 0 { |
| 108 | return nil |
| 109 | } |
| 110 | |
| 111 | // Take the absolute value and keep track of whether it was originally |
| 112 | // negative. |
| 113 | isNegative := n < 0 |
| 114 | if isNegative { |
| 115 | n = -n |
| 116 | } |
| 117 | |
| 118 | // Encode to little endian. The maximum number of encoded bytes is 9 |
| 119 | // (8 bytes for max int64 plus a potential byte for sign extension). |
| 120 | result := make([]byte, 0, 9) |
| 121 | for n > 0 { |
| 122 | result = append(result, byte(n&0xff)) |
| 123 | n >>= 8 |
| 124 | } |
| 125 | |
| 126 | // When the most significant byte already has the high bit set, an |
| 127 | // additional high byte is required to indicate whether the number is |
| 128 | // negative or positive. The additional byte is removed when converting |
| 129 | // back to an integral and its high bit is used to denote the sign. |
| 130 | // |
| 131 | // Otherwise, when the most significant byte does not already have the |
| 132 | // high bit set, use it to indicate the value is negative, if needed. |
| 133 | if result[len(result)-1]&0x80 != 0 { |
| 134 | extraByte := byte(0x00) |
| 135 | if isNegative { |
| 136 | extraByte = 0x80 |
| 137 | } |
| 138 | result = append(result, extraByte) |
| 139 | |
| 140 | } else if isNegative { |
| 141 | result[len(result)-1] |= 0x80 |
| 142 | } |
| 143 | |
| 144 | return result |
| 145 | } |
| 146 | |
| 147 | // Int32 returns the script number clamped to a valid int32. That is to say |
| 148 | // when the script number is higher than the max allowed int32, the max int32 |
no outgoing calls