How to increase an ipv6 address based on mask in java? - operators

i am trying to increment ipv6 address based on mask.
i am getting problem when there is F in place of increment.
could any one plz check this
public String IncrementIPV6ForPrefixLength (String IPv6String, int times) throws UnknownHostException
{
int result , carry = 0, i;
int bits;
int mask=0;
int index=IPv6String.indexOf("/");
mask=Integer.parseInt(IPv6String.substring(index+1, IPv6String.length()));
IPv6String=IPv6String.substring(0, index);
InetAddress iaddr=InetAddress.getByName(IPv6String);
byte[] IPv6Arr=iaddr.getAddress();
if(mask > 128 || mask < 0)
return null;
i = mask/8;
bits = mask%8;
if(bits>0)
{
result = ((int)(IPv6Arr[i]>>(8-bits))) + times;
IPv6Arr[i] =(byte) ((result << (8-bits)) | (IPv6Arr[i] & (0xff >> (bits))));
carry = (result << (8-bits))/256;
times /= 256;
}
i--;
for(;i>=0;i--)
{
result = ((int)IPv6Arr[i]) + ((times + carry)& 0xFF);
IPv6Arr[i] = (byte)(result % 256);
carry = result / 256;
if(carry == 0)
{
iaddr=InetAddress.getByAddress(IPv6Arr);
String s=iaddr.toString();
if(s.indexOf('/') != -1){
s = s.substring(1, s.length()).toUpperCase();
}
StringBuffer buff =new StringBuffer("");
String[] ss = s.split(":");
for(int k=0;k<ss.length;k++){
int Differ = 4 - ss[k].length();
for(int j = 0; j<Differ;j++){
buff.append("0");
}
buff.append(ss[k]);
if(k!=7)buff=buff.append(":");
}
return buff.toString()+"/"+mask;
}
times /= 256;
}
return null;
}
input like this:
FD34:4FB7:FFFF:A13F:1325:2252:1525:325F/48
FD34:41B7:FFFF::/48
FD34:4FBF:F400:A13E:1325:2252:1525:3256/35
output like this
if increment by 1
FD34:4FB8:0000:A13F:1325:2252:1525:325F/48
FD34:41B8:0000::/48
FD34:4FC0:0400:A13E:1325:2252:1525:3256/35
if increment by 2
FD34:4FB8:0001:A13F:1325:2252:1525:325F/48
FD34:41B8:0001::/48
FD34:4FC0:1400:A13E:1325:2252:1525:3256/35
can u plz find where i am doing wrong.

Disregarding the posted code, try to model the operation as a direct numerical operation on the 128-bit number that the IPv6 address really is. Convert to BigInteger and use BigInteger.add.

Related

Arduino convert constant char to unsigned long

I'm asking you to know how to convert a constant char variable[] to a unsigned long variable!
The problem doesn't exist if not for :
I've to convert this value for example "0x20DF10EF" if I convert it to long it return me back "551489775".
What i want is to receive back "0x20DF10EF"!
Hope i've explained well enough my problem!
Best regards D.Tibe!
---- Edit ----
while(O != 'I'){
if(reciver.decode(&results)){
CMD[i] = "0x" + String(results.value, HEX);
CMD[i].toUpperCase();
Val[0] = CMD[i].c_str();
//Vil[0] = CMD[i].c_str();
//for(int i = 0; i < sizeof(Val[0])-1 ;i++)
//{
//}
Byte = String(results.bits, DEC);
delay(1000);
O = 'I';
reciver.resume();
}
This is my code!
I have to convert my Val[0] (that is a Constant char) to Unsigned long variable.
Like said before i'll have a value like this 0x20DF10EF in my constant char and i want to get exactly the same on my unsigned long variable, SO :
Val[0] will be = to 0x20DF10EF and i want to get back the same value but into the unsigned long variable like this
unsigned long Var will be = to 0x20DF10EF
If I understood correctly, you want to parse a const char * string with an hex number and put it into a variable.
If this is correct, there are two ways: using the sscanf function or converting it by hand.
Method 1:
unsigned long result;
if (sscanf(Val[0], "0x%x", &result) != 1)
{
Serial.println("Val[0] is not a valid hex value");
}
Method 2:
unsigned long result = 0;
byte i;
for (i = 2; i < strlen(Val[0]); i++)
{
if ((Val[0][i] >= '0') && (Val[0][i] <= '9'))
{
result = (result << 4) + Val[0][i] - '0';
}
else if ((Val[0][i] >= 'A') && (Val[0][i] <= 'F'))
{
result = (result << 4) + 10 + Val[0][i] - 'A';
}
else if ((Val[0][i] >= 'a') && (Val[0][i] <= 'f'))
{
result = (result << 4) + 10 + Val[0][i] - 'a';
}
else
{
Serial.println("Val[0] is not a valid hex value");
break;
}
}
By the way, adding 0x in front of the string is useless for this conversion. If you can, remove it and then replace "0x%x" with "%x" in the sscanf solution, or i = 2 with i = 0 in the hand-made one.

Better way to Convert multiple byte Binary to Signed Decimal in Objective C

As I know, it is easy to convert single byte to signed decimal by
char source_binary = '\xff' //-1
int signedInt = (int)source_binary //signedInt = -1
But I would like to know if any better way to handle in multiple byte
//Example -2, represent as 0xFFFE. I got two byte as follow:
char highByte = '\xff'
char lowByte = '\xfe'
Here is my solution:
- (int) convertTwoBytesBinaryToSignedInt:(char)highByte :(char)lowByte
{
int retValue = 0;
int hiValue = (int) highByte;
int loValue = 0;
if ((int)lowByte < 0)
loValue = 0 - ((lowByte ^ '\xff') + 1);
else
loValue = 0 - 256 + (int)lowByte;
if (hiValue < 0) {
//Negative Binary
retValue = (((hiValue+1)*256)+ loValue);
} else {
//Postive Binary
retValue = ((int)highByte)*256+(int)lowByte;
}
return retValue;
}
Would you please advise me any better way to convert it to signed decimal?
int word = ((int) highByte << 8) | (unsigned char) lowByte;
EDIT: insufficient testing. :)

Constructing bitmask ? bitwise packet

I have been wanting to experiment with this project Axon with an iOS app connecting over a tcp connection. Towards the end of the doc the protocol is explained as so
The wire protocol is simple and very much zeromq-like, where is a BE 24 bit unsigned integer representing a maximum length of roughly ~16mb. The data byte is currently only used to store the codec, for example "json" is simply 1, in turn JSON messages received on the client end will then be automatically decoded for you by selecting this same codec.
With the diagram
octet: 0 1 2 3 <length>
+------+------+------+------+------------------...
| meta | <length> | data ...
+------+------+------+------+------------------...
I have had experience working with binary protocols creating a packet such as:
NSUInteger INT_32_LENGTH = sizeof(uint32_t);
uint32_t length = [data length]; // data is an NSData object
NSMutableData *packetData = [NSMutableData dataWithCapacity:length + (INT_32_LENGTH * 2)];
[packetData appendBytes:&requestType length:INT_32_LENGTH];
[packetData appendBytes:&length length:INT_32_LENGTH];
[packetData appendData:data];
So my question is how would you create the data packet for the Axon request, I would assume some bit shifting, which I am not too clued up on.
Allocate 1 array of char or unsigned char with size == packet_size;
Decalre constants:
const int metaFieldPos = 0;
const int sizeofMetaField = sizeof(char);
const int lengthPos = metaFieldPos + sizeofMetaField;
const int sizeofLengthField = sizeof(char) * 3;
const int dataPos = lengthPos + sizeofLengthField;
If you got the data and can recognize begining of the packet, you can use constants above to
navigate by pointers.
May be these functions will help you (They use Qt, but you can easily translate them to library, that you use)
quint32 Convert::uint32_to_uint24(const quint32 value){
return value & (quint32)(0x00FFFFFFu);
}
qint32 Convert::int32_to_uint24(const qint32 value){
return value & (qint32)(0x00FFFFFF);
}
quint32 Convert::bytes_to_uint24(const char* from){
quint32 result = 0;
quint8 shift = 0;
for (int i = 0; i < bytesIn24Bits; i++) {
result |= static_cast<quint32>(*reinterpret_cast<const quint8 *>(from + i)) << shift;
shift+=bitsInByte;
}
return result;
}
void Convert::uint32_to_uint24Bytes(const quint32 value, char* from){
quint8 shift = 0;
for (int i = 0; i < bytesIn24Bits; i++) {
const quint32 buf = (value >> shift) & 0xFFu;
*(from + i) = *reinterpret_cast<const char *>(&buf);
shift+=bitsInByte;
}
}
QByteArray Convert::uint32_to_uint24QByteArray (const quint32 value){
QByteArray bytes;
bytes.resize(sizeof(value));
*reinterpret_cast<quint32 *>(bytes.data()) = value;
bytes.chop(1);
return bytes;
}

arm cortex m3 display

hi i am working on arm controller lm3s8962 i m not able to understand the code below as per my understanding it is checking if the character is from the array or not, which he created using the ascii characters{i.e in the while loop : while(*pcStr != 0) },
i am not able to get what he is doing in the code after the line "Build and display the character buffer" plz can anyone explain this
void
RIT128x96x4StringDraw(const char *pcStr, unsigned long ulX,
unsigned long ulY, unsigned char ucLevel)
{
unsigned long ulIdx1, ulIdx2;
unsigned char ucTemp;
//
// Check the arguments.
//
ASSERT(ulX < 128);
ASSERT((ulX & 1) == 0);
ASSERT(ulY < 96);
ASSERT(ucLevel < 16);
//
// Setup a window starting at the specified column and row, ending
// at the right edge of the display and 8 rows down (single character row).
//
g_pucBuffer[0] = 0x15;
g_pucBuffer[1] = ulX / 2;
g_pucBuffer[2] = 63;
RITWriteCommand(g_pucBuffer, 3);
g_pucBuffer[0] = 0x75;
g_pucBuffer[1] = ulY;
g_pucBuffer[2] = ulY + 7;
RITWriteCommand(g_pucBuffer, 3);
RITWriteCommand(g_pucRIT128x96x4VerticalInc,
sizeof(g_pucRIT128x96x4VerticalInc));
//
// Loop while there are more characters in the string.
//
while(*pcStr != 0)
{
//
// Get a working copy of the current character and convert to an
// index into the character bit-map array.
//
ucTemp = *pcStr++ & 0x7f;
if(ucTemp < ' ')
{
ucTemp = 0;
}
else
{
ucTemp -= ' ';
}
//
// Build and display the character buffer.
//
for(ulIdx1 = 0; ulIdx1 < 6; ulIdx1 += 2)
{
//
// Convert two columns of 1-bit font data into a single data
// byte column of 4-bit font data.
//
for(ulIdx2 = 0; ulIdx2 < 8; ulIdx2++)
{
g_pucBuffer[ulIdx2] = 0;
if(g_pucFont[ucTemp][ulIdx1] & (1 << ulIdx2))
{
g_pucBuffer[ulIdx2] = (ucLevel << 4) & 0xf0;
}
if((ulIdx1 < 4) &&
(g_pucFont[ucTemp][ulIdx1 + 1] & (1 << ulIdx2)))
{
g_pucBuffer[ulIdx2] |= (ucLevel << 0) & 0x0f;
}
}
//
// Send this byte column to the display.
//
RITWriteData(g_pucBuffer, 8);
ulX += 2;
//
// Return if the right side of the display has been reached.
//
if(ulX == 128)
{
return;
}
}
}
}
He is doing some bit manipulations to build up bytes.
x |= y is the same as x = x | y, which keeps all the 1s in x and also changes some of the 0s to 1 if y has a 1 in the same position.
1 << i is a byte with a single 1 bit in the ith position from the right.
x = y & 0xf0 copies only the left 4 bits of y into x.
So he is looking up values in an array, checking particular bits of those values, then filling up another array with number created from those bits. You will have to work out the particulars for yourself.

Arduino replace code

I'm very new to Arduino and C programming.
I'm making a GPS speedo and I'm trying to read in some serial, store a value from a substring and echo it back via serial.
At the moment I'm having problems storing the substring.
I've gotten to the point where I'm able to get some data between < and >.
But the data doesn't come in like that. It's a NMEA data stream and the data I want is between ,N, and ,K,.
So I've been trying to replace ,N, with < and ,K, with > .
Just can't get it to work. I get error: request for member 'replace' in 'c', which is of non-class type 'char'
Here's my code so far....
int indata = 0;
int scrubdata = 0;
char inString[32];
int stringPos = 0;
boolean startRead = false; // is reading?
void setup() {
Serial.begin(4800);
}
void loop() {
String pageValue = readPage();
Serial.print(pageValue);
}
String readPage(){
//read the page, and capture & return everything between '<' and '>'
stringPos = 0;
memset( &inString, 0, 32 ); //clear inString memory
while(true){
if (Serial.available() > 0) {
char c = Serial.read();
c.replace(",N,", "<");
c.replace(",K,", ">");
if (c == '<' ) { //'<' is our begining character
startRead = true; //Ready to start reading the part
}
else if(startRead){
if(c != '>'){ //'>' is our ending character
inString[stringPos] = c;
stringPos ++;
}
else{
//got what we need here! We can disconnect now
startRead = false;
return inString;
}
}
}
}
}
By Default:
Serial.read() returns an int if you must process the data this way, try casting it to char with:
char c = (char) Serial.read();
Another way to do this:
Would be to seek your beginning string (discarding un-needed data) using Serial.find() then reading data until you met your end character ",K," with Serial.readBytesUntil()
Something like this would work quite well:
char inData[64]; //adjust for your data size
Serial.setTimeout(2000); //Defaults to 1000 msecs set if necessary
Serial.find(",N,"); //Start of Data
int bRead = Serial.readBytesUntil(",K,", inData, 64); //Read until end of data
inData[bRead] = 0x00; //Zero terminate if using this as a string
return inData;