Function asBytes [src]
Given a pointer to a single item, returns a slice of the underlying bytes, preserving pointer attributes.
Prototype
pub fn asBytes(ptr: anytype) AsBytesReturnType(@TypeOf(ptr))
Example
test asBytes {
const deadbeef = @as(u32, 0xDEADBEEF);
const deadbeef_bytes = switch (native_endian) {
.big => "\xDE\xAD\xBE\xEF",
.little => "\xEF\xBE\xAD\xDE",
};
try testing.expect(eql(u8, asBytes(&deadbeef), deadbeef_bytes));
var codeface = @as(u32, 0xC0DEFACE);
for (asBytes(&codeface)) |*b|
b.* = 0;
try testing.expect(codeface == 0);
const S = packed struct {
a: u8,
b: u8,
c: u8,
d: u8,
};
const inst = S{
.a = 0xBE,
.b = 0xEF,
.c = 0xDE,
.d = 0xA1,
};
switch (native_endian) {
.little => {
try testing.expect(eql(u8, asBytes(&inst), "\xBE\xEF\xDE\xA1"));
},
.big => {
try testing.expect(eql(u8, asBytes(&inst), "\xA1\xDE\xEF\xBE"));
},
}
const ZST = struct {};
const zero = ZST{};
try testing.expect(eql(u8, asBytes(&zero), ""));
}
Source
pub fn asBytes(ptr: anytype) AsBytesReturnType(@TypeOf(ptr)) {
return @ptrCast(@alignCast(ptr));
}