Archive

Posts Tagged ‘C++’

C++ itoa

June 11th, 2009 David No comments

It’s super annoying that c/c++ has an atoi function but not an itoa. I’ve had to implement this countless times in my code, and I have a nice snipet that has worked well for me. This function supports output in an base from 2 to 16, and has a “pad” option that add a leading “0″ if the number of chars in the output string are not a multiple of two. This is nice for hex formatting.

string itoa(int value, int base, bool pad){
    enum { kMaxDigits = 35 };
    string buf;
    buf.reserve( kMaxDigits);

    //check that the base is valid
    if(base < 2 || base > 16) return buf;
    int quotient = value;

    //translate number to string with base
    do{
        buf += “0123456789abcdef”[std::abs( quotient % base )];
        quotient /= base;
    } while( quotient );

    //append negative sign for base 10
    if(value <0 && base == 10) buf += '-';

    reverse( buf.begin(), buf.end() );

    if(pad && base != 10) if(buf.length()%2 == 1) buf = "0" + buf;

    return buf;
} 
Categories: C++, Code Tags:

A simple bootloader…

June 11th, 2009 David No comments

If you have ever used a Linux distro on an embedded system you know that a bootloader is a necessity. I’ve been working with PetaLinux for the Xilinx MicroBlaze and we have been using FS-boot to launch U-boot and then bring up Peta. However, recently I switched to BlueCat linux to take advantage of the MicroBlaze’s MMU. However, BlueCat doesn’t document a clear way to boot from flash. Below is some simple code to boot BlueCat. Note: the concept was taken from a Xilinx app note.

#include <xparams.h>
#define KDI_FLASH_LOC 0xXXXXXXXX //location of the linux image in flash
#define KDI_DDR_LOC 0xXXXXXXXX //location in DDR that you want your image to end up
#define KDI_LEN 0xXXXXXXXX //length of your image in bytes

main(){

uint8_t* kdi_flash_ptr = (uint8_t*)KDI_FLASH_LOC;
uint8_t* kdi_ddr_ptr = (uint8_t*)KDI_DDR_LOC;

void* laddr;

memcpy(kdi_flash_ptr, kdi_ddr_ptr, KDI_LEN);

laddr = (void*)KDI_DDR_LOC;
(*laddr)();

}

You can use XPS to load your KDI file into flash, and then compile the bootloader into your bitstream, load the FPGA, and you are off!

Categories: Code, Embedded, Linux, Xilinx Tags: , , ,