1

I want to convert a decimal number to hex format in a way that only bit corresponding to that decimal number is set. For example, for input 0, bit 0 should be set and results in

>  paste("0x", sprintf("%032x",2^(0)),sep="")  
[1] "0x00000000000000000000000000000001"

and for 1, bit one should be set, resulting in

>  paste("0x", sprintf("%032x",2^(1)),sep="")  
[1] "0x00000000000000000000000000000002"

This works till 30

> paste("0x", sprintf("%032x",2^(30)),sep="")  
[1] "0x00000000000000000000000040000000"  

but does not work for values larger than that

>  paste("0x", sprintf("%032x",2^(32)),sep="")  
Error in sprintf("%032x", 2^(32)) :invalid format '%032x'; use format %f, %e, %g or %a for numeric objects

Any idea how to get around this?

Saltaf
  • 65
  • 6

1 Answers1

0

I think you're "overloading" the sprintf function. That is, your type is set to "%032x" and then you pass in the value 2^(32) which the function doesn't see as "%032x" so you get an error.

Here's a couple of semi-related questions, but I don't think these would count as exact duplicates: why causes invalid format '%d in R?

hex to string formatting conversion in python

Why does a 32-bit OS support 4 GB of RAM?

Community
  • 1
  • 1
William
  • 154
  • 9