#Is it possible to obtain address to certain byte of number?

1 messages · Page 1 of 1 (latest)

bleak cove
#
val: i32 = 0x123456;
ptr: *u8 = /* get pointer to second byte of val */;
brisk peak
#

std.mem.asBytes(&val)[1]?

#

or &@ptrCast([*]u8, &val)[1]

bleak cove
#
const std = @import("std");

pub fn main() void {
    var val: i32 = 0x123456;
    var ptr: *u8 = &@ptrCast([*]u8, &val)[1];

    std.debug.print("{}", .{*ptr});
}

error: expected type 'type', found '*u8'
std.debug.print("{}", .{*ptr});
how do you print that?

#

nevermind

#

i forgot

#

its not c

#

old habits die hard

#
const std = @import("std");

pub fn main() void {
    var val: i32 = 0x12345678;
    var ptr: *u4 = &@ptrCast([*]u4, &val)[1];

    std.debug.print("{}", .{ptr.*});
}
#

why this prints 6 instead of 7?

hexed relic
#

because byte is 8 bits, not 4

#

78 is the same byte, the next byte is 56, but 5 is cut off because of the cast to u4

bleak cove
#

so i cant cast it into array of u4?

hexed relic
#

you can, but it makes no sense

bleak cove
#

var ptr: *u4 = &@ptrCast([*]u4, &val)[1];
val is 32bit and im casting it into array of u4 so it should be 8 * 4bit and each digit of hex is 4 bit

#

i still dont get it

hexed relic
#

the smallest addressable unit is u8

bleak cove
#

i see

hexed relic
#

at least on most architectures

bleak cove
#

ok thanks