File tree 1 file changed +9
-4
lines changed
1 file changed +9
-4
lines changed Original file line number Diff line number Diff line change @@ -2758,11 +2758,11 @@ pub const hex_charset = "0123456789abcdef";
2758
2758
2759
2759
/// Converts an unsigned integer of any multiple of u8 to an array of lowercase
2760
2760
/// hex bytes, little endian.
2761
- pub fn hex (x : anytype ) [@sizeOf ( @ TypeOf (x )) * 2 ]u8 {
2761
+ pub fn hex (x : anytype ) [2 * @divExact ( @typeInfo ( @ TypeOf (x )). int . bits , 8 ) ]u8 {
2762
2762
comptime assert (@typeInfo (@TypeOf (x )).int .signedness == .unsigned );
2763
- var result : [ @sizeOf (@TypeOf (x )) * 2 ] u8 = undefined ;
2764
- var i : usize = 0 ;
2765
- while ( i < result . len / 2 ) : ( i += 1 ) {
2763
+ const octet_count = @typeInfo (@TypeOf (x )). int . bits / 8 ;
2764
+ var result : [ 2 * octet_count ] u8 = undefined ;
2765
+ for (0 .. octet_count ) | i | {
2766
2766
const byte : u8 = @truncate (x >> @intCast (8 * i ));
2767
2767
result [i * 2 + 0 ] = hex_charset [byte >> 4 ];
2768
2768
result [i * 2 + 1 ] = hex_charset [byte & 15 ];
@@ -2771,6 +2771,11 @@ pub fn hex(x: anytype) [@sizeOf(@TypeOf(x)) * 2]u8 {
2771
2771
}
2772
2772
2773
2773
test hex {
2774
+ {
2775
+ const x = hex (@as (u48 , 0x1234_5678_3210 ));
2776
+ try std .testing .expect (x .len == 12 );
2777
+ try std .testing .expectEqualStrings ("103278563412" , & x );
2778
+ }
2774
2779
{
2775
2780
const x = hex (@as (u32 , 0xdeadbeef ));
2776
2781
try std .testing .expect (x .len == 8 );
You can’t perform that action at this time.
0 commit comments