| ... | ... | @@ -2555,6 +2555,21 @@ test "bytes.hex" { |
| 2555 | 2555 | try expectFmt("lowercase: 000ebabe\n", "lowercase: {x}\n", .{fmtSliceHexLower(bytes_with_zeros)}); |
| 2556 | 2556 | } |
| 2557 | 2557 | |
| 2558 | /// Encodes a sequence of bytes as hexadecimal digits. |
| 2559 | /// Returns an array containing the encoded bytes. |
| 2560 | pub fn bytesToHex(input: anytype, case: Case) [input.len * 2]u8 { |
| 2561 | if (input.len == 0) return [_]u8{}; |
| 2562 | comptime assert(@TypeOf(input[0]) == u8); // elements to encode must be unsigned bytes |
| 2563 | |
| 2564 | const charset = "0123456789" ++ if (case == .upper) "ABCDEF" else "abcdef"; |
| 2565 | var result: [input.len * 2]u8 = undefined; |
| 2566 | for (input, 0..) |b, i| { |
| 2567 | result[i * 2 + 0] = charset[b >> 4]; |
| 2568 | result[i * 2 + 1] = charset[b & 15]; |
| 2569 | } |
| 2570 | return result; |
| 2571 | } |
| 2572 | |
| 2558 | 2573 | /// Decodes the sequence of bytes represented by the specified string of |
| 2559 | 2574 | /// hexadecimal characters. |
| 2560 | 2575 | /// Returns a slice of the output buffer containing the decoded bytes. |
| ... | ... | @@ -2575,6 +2590,13 @@ pub fn hexToBytes(out: []u8, input: []const u8) ![]u8 { |
| 2575 | 2590 | return out[0 .. in_i / 2]; |
| 2576 | 2591 | } |
| 2577 | 2592 | |
| 2593 | test "bytesToHex" { |
| 2594 | const input = "input slice"; |
| 2595 | const encoded = bytesToHex(input, .lower); |
| 2596 | var decoded: [input.len]u8 = undefined; |
| 2597 | try std.testing.expectEqualSlices(u8, input, try hexToBytes(&decoded, &encoded)); |
| 2598 | } |
| 2599 | |
| 2578 | 2600 | test "hexToBytes" { |
| 2579 | 2601 | var buf: [32]u8 = undefined; |
| 2580 | 2602 | try expectFmt("90" ** 32, "{s}", .{fmtSliceHexUpper(try hexToBytes(&buf, "90" ** 32))}); |