When I print a signed integer like this: fmt.printf("{:8b}", i8(-12)) it renders it as 000-1100 but I think it should be 11110100 (which is how it appears when showing it as a local var in RemedyBG, in 2s-complement format) - is there a formatting flag I need to use to print the raw binary bits? I can cast it to u8 to see the raw bits, but is there a way to do this just using printf flags?
#Is there a way to get Odin to print/format binary as-is, without printing `-`?
1 messages · Page 1 of 1 (latest)
First, I think I would classify that as a bug in the fmt package the way it handles the sign and padding. If it printed -0001100 instead I think that would be as expected.
So if you want the "raw bits" then you would need to cast it to unsigned.
Imagine you used :8X instead. Wouldn't you expect it to print -000000C ? I don't think the integer base itself should decide what should be signed or not.
I don't know what would be right re: printing as hex, I don't think I've ever printed a negative number as hex. It's just odd to me that printing as binary doesn't print the in-memory representation (or rather, that there isn't a way to tell printf that's what you want) - I'm parsing binary (8086 instructions) and so I want to see what's really there rather than it being reinterpreted if that makes sense. Easy answer though for this is just cast to u8/u16 etc - that'll do the trick fine. I was trying to understand what was going on here
Easiest to understand would be to just think of it as an integer base representation of any number. A signed decimal number is no different from a signed hexadecimal, or signed binary number.
I was also very surprised to find that C's printf doesn't print binary bits at all and the standard answer to that is to bit shift and print each bit yourself. It's nice to have a stdlib that helps out much more than that!
Of course, fmt could have an additional verb for something that prints the raw bits, but I don't know if that's needed when you could simply pass an unsigned number instead?
Yeah I don't have a suggestion about whether it'd help to have a verb to print raw bits for signed ints. Clearly yes casting to unsigned solves that, and so would showing the variable or whatever in a debugger. I think maybe a bit of a mention in the docs might help because it's counterintuitive to me at least
I suppose what I was expecting was "%b" to print as 2s-complement binary, which you might want sometimes, and not others. So maybe a flag to tell it you want that could be useful (but not essential as there's such an easy workaround)
I created this bug report for the padding/sign issue https://github.com/odin-lang/Odin/issues/2431
In my example code there I used a negative binary literal. Maybe that helps see why %b works the way it does?